Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×

Pthreads vs Win32 threads 385

An anonymous reader writes "It's interesting when different people have different opinions. While I was searching for something on Intel's website, I came across an article on why Windows threads are better than Posix threads. Curiously, I also came across this article on why Posix Pthreads are better that Win32 threads. The thing is, both of these articles are written by the same author!

So who is right (metaphorically speaking?), or what has changed since the first article was written?"
This discussion has been archived. No new comments can be posted.

Pthreads vs Win32 threads

Comments Filter:
  • quothe the poster (Score:5, Insightful)

    by TinBromide ( 921574 ) on Monday February 26, 2007 @10:02AM (#18152856)
    "or what has changed since the first article was written?"

    Vista's release and a massive advertising campaign/increase in revinue for microsoft partners?
    • by Nom du Keyboard ( 633989 ) on Monday February 26, 2007 @10:59AM (#18153594)
      "or what has changed since the first article was written?"

      What has likely changed is were the paycheck came from this week.

      • Nothing has changed (Score:5, Informative)

        by einhverfr ( 238914 ) <chris DOT travers AT gmail DOT com> on Monday February 26, 2007 @09:24PM (#18162282) Homepage Journal
        Read the two articles closely, and side by side. What you will see is that both articles have an identical structure and make simply the opposite cases. The opening is almost verbatim between the two articles, for example.

        Although there are three year between the articles and people change, this looks to me like someone trying to write different articles from different viewpoints rather than proving that one is best. If he really had changed his mind, maybe he would have said so and referenced his previous article rather than copying it?
    • by should_be_linear ( 779431 ) on Monday February 26, 2007 @11:21AM (#18153894)
      I have different theory: Dude has 2 separate threads in his brain. Comparing pthreads to Win32 threads only exposed dangerous race condition producing funny effects in his blog.
      • by Hal_Porter ( 817932 ) on Monday February 26, 2007 @11:42AM (#18154210)
        Q)Why did the multithreaded chicken cross the road?
        A)to To other side. get the

        Q)Why did the multithreaded chicken cross the road?
        A)other to side. To the get

        • by 0xABADC0DA ( 867955 ) on Monday February 26, 2007 @02:44PM (#18157338)
          Q) Which came first, the multithreaded chicken or the multithreaded egg?
          A) They came at the same time, but the multithreaded chicken terminated first.

          Q) Which came first, the multithreaded chicken or the multithreaded egg?
          A) Neither; mt egg could not acquire chicken-lock from mt chicken. mt chicken could not acquire egg-lock from mt egg.

          Q) Which came first, the multithreaded chicken or the multithreaded egg?
          A) Multithreaded egg, but it overwrote its DNA while still in use and became mt turkey.
      • Re:quothe the poster (Score:4, Informative)

        by ThePhilips ( 752041 ) on Monday February 26, 2007 @12:00PM (#18154506) Homepage Journal

        I can only hope that's funny.

        This is [censored] reality. Nobody program for Windows because he likes to program for Windows: people do that mainly for money. "Work" they say.

        Whatever you appear to like in competing implementations is irrelevant: M$ and corporate decision makers leaves you no choice.

        And there are really only two choices: (1) you go insane and start loving whatever management tells you to love or (2) you search for another job. Since the guy is with Intel, he's likely to have good payroll and option (2) doesn't ring any bells.

        [ I hope you have noticed that "I love POSIX" post is from year 2003 - and "I love Windows" from 2006. But honestly it all looks more like joke. ]

        I'd say from personal experience, that threading in Windows is total mess. POSIX threads might look limiting - but on other side you need to resort to threads in *nix ... well you do not have to resort to threads all. It is your own programmer's choosing: to use threads or to use state machines and async I/O. Under Windows bugs plagued/plague/will plague async I/O and programmers have no choice other then to use threads for sockets and file I/O. So under Windows you use threads for everything (except GUI which is restricted to "main thread"), while in *nix it is norm to see threads only in applications which want to take advantage of multi-processor systems for heavy computational tasks: math, code cracking, video encoding, etc. Heavy I/O tasks in *nix are all single threaded: Apache, Squid, MySQL, PostgreSQL, postfix/sendmail/exim, etc. (Though most now support optional multi-threading too - for really busy servers.)

        • by Korin43 ( 881732 ) on Monday February 26, 2007 @12:24PM (#18154930) Homepage
          What are you talking about? Plenty of people code for Windows, we call them "virus writers". ;)
        • Re:quothe the poster (Score:5, Interesting)

          by Courageous ( 228506 ) on Monday February 26, 2007 @12:26PM (#18154974)
          Nobody program for Windows because he likes to program for Windows...

          To the contrary. I work on Linux systems at work, and play on Windows, using .NET (C#) at home, for fun. .NET is a genuine pleasure to work with: a better java than java, I say. It may be an asset of the evil empire, and it may not be multiplatform, but I find those to be its only weaknesses.

          C//
          • by Listen Up ( 107011 ) on Monday February 26, 2007 @11:25PM (#18163088)
            a better java than java, I say

            Bullshit. I develop full-time in J2SE/J2EE and now C# (.NET 2.0/3.0) as well. If you are just some beginner/non-developer, writing slightly more complicated Hello World applications, then you are not going to see any real difference between Java or .NET or . When it comes to writing real applications, such as applications leveraging massive amounts of long running transactional processes, enterprise message queuing systems (the existing MS message queuing systems are a joke), almost any SOA application (.NET 3.0 is getting better), almost any distributed scalable enterprise applications, the ability to develop an enterprise software solution on Windows and deploy it to Solaris/Linux/etc. with zero code changes (Mono you say...Not even close), etc. etc. etc. .NET is still 10 years back. How about a .NET equivalent to EJB 3.0? Not even close. Sure, the syntax of C# is nice, like Java, which it should be because Microsoft copied %99.999 of the syntax directly from Java.

            The features and functionality available in Java 6 are astounding and are aimed squarely at making J2SE on the desktop, making J2ME ubiquitous in mobile devices, as well as securely putting J2EE years ahead of it competition. Java 7 is looking to be even more exciting.

            For everyone whose last memory of Java is 10 years ago, you need to look at it again. Aside from basic single platform desktop applications, .NET is where Java was 10 years ago. Hell, Visual Studio is not even written in .NET nor any major application at this point (Office? IIS? Anyone?). Any real .NET app servers? And they certainly aren't running these applications on Mono. When I see Office running natively on Mono on Linux or OS X, I might be more interested. So Microsoft added automatic memory management and a common language runtime (with the intent to allow the possibility of cross-platform development on paper) to its main development languages. Yay. That doesn't make .NET equal to Java.

            All of the enterprise .NET developers at the company I work at as well as many of our clients are excited about .NET 2.0/3.0 web services because .NET is finally starting to get services that have been available in Java for years. That is the true point of .NET in the development world. People on Slashdot need to stop drinking the beginner/non-developer kool-aid.
        • Re:quothe the poster (Score:5, Informative)

          by PitaBred ( 632671 ) <slashdot@@@pitabred...dyndns...org> on Monday February 26, 2007 @12:37PM (#18155176) Homepage
          Did you notice the other similarities?

          Initial (2003) article:

          I've used both POSIX threads (Pthreads) and Win32 threads APIs and I believe that Pthreads has the better programming model of the two. While each threading method can create threads, destroy threads, and coordinate interactions between threads, the reason I make this claim is the simplicity of use and elegance of design of Pthreads. Let me illustrate with a few examples.
          And in the later article:

          I've used both POSIX threads (Pthreads) and Windows threads APIs, and I believe that Windows has the better programming model of the two. While each threading method can create threads, destroy threads, and coordinate interactions between threads, the reason I make this claim is the simplicity of use and elegance of design of the Windows threads API. This is all from the perspective of multithreaded code developers or maintainers. Let me illustrate with a few examples.
          It's not plagiarism because he copied from himself and just added a few edits, but c'mon... how lazy of a shill can you be?
  • switch? (Score:2, Interesting)

    by raffe ( 28595 ) *
    Looks like he just switched the words in the articles...?
  • $Money$ (Score:5, Insightful)

    by ArcherB ( 796902 ) * on Monday February 26, 2007 @10:04AM (#18152890) Journal
    So who is right (metaphorically speaking?), or what has changed since the first article was written?"

    Who was paying for it.
  • It's interesting when different people have different opinions.

    Not so long ago, to some extent even today, there have been certain parts of this planet where that could have been called interesting indeed, but that only by some elements of their governments. Now, you calling that interesting makes an interesting picture of you.
     
  • by arlo5724 ( 172574 ) <jacobw56 AT gmail DOT com> on Monday February 26, 2007 @10:06AM (#18152920)
    ( Pthreads >= Win32 threads ) and ( Win32 threads >= Pthreads ) => Pthreads = Win32 threads
  • by DelawareBoy ( 757170 ) on Monday February 26, 2007 @10:07AM (#18152930)
    The blog entry that points out the superiority of Win32 threads is dates to October 2006. The PThread example is a reply to a posting from 2003. I have a feeling that as the author worked more and more with the different threading models, he seems to have a more matured opinion. However, this being Slashdot, the Win32 Threading model is by definition inferior, since Microsoft has no intelligent engineers whatsoever and the author of the article was originally correct and should have never have looked further.
    • by Anonymous Coward on Monday February 26, 2007 @10:11AM (#18153010)
      Except that the 2006 entry is essentially a structural copy of the 2003 entry, just with some wording changes. He even uses the same arguments against PThreads in the second entry that he used to support it in the first. Weird...
      • Re: (Score:3, Interesting)

        by TopherC ( 412335 )
        If the arguments in these articles are actually interchangeable, then either:

        1) These arguments have no rational basis, and both are BS (unjustified opinions).

        2) There are serious factual errors in at least one article.

        I wonder which one of these is closer to the truth? I'm guessing it's #1. Either way, the author can no longer be taken seriously.
    • by AKAImBatman ( 238306 ) * <akaimbatmanNO@SPAMgmail.com> on Monday February 26, 2007 @10:18AM (#18153078) Homepage Journal

      I have a feeling that as the author worked more and more with the different threading models, he seems to have a more matured opinion.

      Normally I'd agree with you. But if you read both articles, you realize that his intentions may be a bit less honorable. The Win32 article is the exact same article, but with the conclusions changed. Maturing opinions usually result in some discussion of why one has changed their mind (even if it's only mentioned in passing) and/or a deep explanation of what caused their mind to change. This smells more like an attempt to play both sides.

      Of course, it could be that the author is simply not comfortable with writing. He could be looking to make a quick buck by taking a simple forum post of his and modifying it to reflect his current opinion. It's worth giving him the benefit of the doubt on, but I am certainly suspicious.
      • NOTE: This quote is not the previous authors comment, but a modification.

        Normally I'd agree with you. But if you read both articles, you realize that his intentions may be a bit more honorable. The Win32 article is the exact same layout, but with pieces of content and conclusion changed. Maturing opinions usually result in some discussion of why one has changed their mind (even if it's only mentioned in passing) and/or a deep explanation of what caused their mind to change. This smells more like he was embarrased about his old oppinions.

        Of course, it could be that the author is simply not comfortable with writing. He could be looking to make a quick buck by taking a simple forum post of his and modifying it to reflect his current opinion. It's worth giving him the benefit of the doubt on, but I am certainly suspicious.

        The content of this quote is exactly the same as the content of the parent like the content of the two articles are exactly the same.

        There's a lot of different information in them, they just follow a very similar, and possibly copy and pasted format. Normally I would agree that a discussion of the change of veiw would be appropraite, and actually I still do agree, but your reply was a bit harsh. The two articles to me combine to say:

        (

        • I learned Win32 threads first, and I wouldn't say they are particularly hard. I then learned POSIX threads, used them for a bit, and then had to help someone else with their Win32 threads code. I found this quite hard, since Win32 threads seemed to be missing a few of the things I routinely used in POSIX threads. Do Win32 threads have condition variables these days?
  • by hey ( 83763 ) on Monday February 26, 2007 @10:08AM (#18152946) Journal
    If you are programming on Widows I would recommend Windows threads, while on *nix Pthreads are a better choice.
    • Re: (Score:3, Funny)

      by drinkypoo ( 153816 )

      If you are programming on Widows I would recommend Windows threads, while on *nix Pthreads are a better choice.

      If you are programming on Widows, may I suggest a chair? It's typically more comfortable.

    • Re: (Score:3, Funny)

      by BalkanBoy ( 201243 )
      > If you are programming on Widows ...

      I'd say if you're programming on widows, you need to find a way to replace the defunct parent process by forking yourself into a parent... but this is impossible since the child process(es) will absolutely refuse to have their defunct parent re-forked by some other forker who's coming in from a different, unsafe, unprotected location. Thus threading in lightly, and establishing shared values with the children whose parent has defuncted might be your only option o

  • Eeew, threads. (Score:3, Informative)

    by vadim_t ( 324782 ) on Monday February 26, 2007 @10:10AM (#18152976) Homepage
    Here's the one thing Windows needs: fork()

    Threads have all sorts of nasty issues and pitfalls on any platform. Meanwhile, fork() is beautifully simple, and fork + socketpair lacks pretty much all of them. The speed may be a bit lower, but there's the great benefit of simpler and much safer code.
    • Re:Eeew, threads. (Score:4, Informative)

      by Cheesey ( 70139 ) on Monday February 26, 2007 @10:32AM (#18153234)
      On Windows, there is a much higher penalty associated with spawning a child process than on Unix. This makes using threads much more attractive - they are faster.

      I don't know why the Windows equivalent of fork() is slower than the Unix fork(). Perhaps it is a historical thing. Unix programs often use fork() - shell scripts use it all the time (this is one reason why a Python or Perl script is often faster). I'm just guessing now, but perhaps Unix fork() is efficient because it is frequently used and has therefore been optimised in various ways (e.g. memory is only copied if there is a write on Linux). Whereas on Windows, those optimisations are not necessary.
      • Re: (Score:3, Interesting)

        > (e.g. memory is only copied if there is a write on Linux)

        Not just Linux.

        I think this was the case with SVR4 and BSD4.3.

        But that was a LONG time ago... memory gets fuzzy..

        It's entirely probable that the first time I read about fork being copy-on-write was in Tannenbaum's yellow book, so it might even be in Minix.

        It has certainly been the case as far as I'm aware in every non-toy Unix and UNIX for at least a decade.

        But then again, I don't care, since I'm not a kernel developer. :)
        • Re: (Score:3, Interesting)

          by TheRaven64 ( 641858 )
          Fork() is a hold over from a very long time ago. The very old machines did not have protected memory, and so each context switch meant dumping the contents of memory and loading a new process image. If you did a fork(), you just had to do the dump, but not the reload and you got a copy of the parent process's address space for free. Now, there are lots of hacks to try to make it fast (e.g. copy-on-write and vfork()). We keep using it because that's how UNIX has always worked, not because it's actually s
          • Re:Eeew, threads. (Score:4, Interesting)

            by EvanED ( 569694 ) <evaned@@@gmail...com> on Monday February 26, 2007 @01:47PM (#18156372)
            Maybe it originated like that, but the fork/exec model of starting a new process has another really big benefit as compared to, say, Windows's CreateProcesses, which is that it's easier to control the execution environment of the child process.

            Running as root and want to start the process with lower privileges? Do fork - setuid - exec. Want to open pipes to the child? Do pipe - fork - a couple calls in the child to connect the pipes to stdin/out - exec.

            By contrast, Windows has to encapsulate anything you want to be able to do to set up the child's environment in the CreateProcess call. That's why it takes 9 arguments, one of which is a flags argument where there are 15 flags, and one of which is a pointer to a struct with 17 fields (one of which takes another 9 flags).
          • Re: (Score:3, Interesting)

            On the contrary, fork() is still sensible even today. Especially the copy-on-write implementations. fork() is ideal for saving memory in scripting languages.
            Imagine a Perl program, which requires about 35 MB of memory (25 MB for the parsed code, 10 MB for actual work). The user wants to run 6 instances of the program. Without fork (that is, on Windows) the user will need 210 MB of memory. On Unix I can use fork() and the user will only need about 100 MB of memory because the parsed code is shared between in
      • Re: (Score:3, Insightful)

        by mrsbrisby ( 60242 )

        On Windows, there is a much higher penalty associated with spawning a child process than on Unix. This makes using threads much more attractive - they are faster.

        No, it doesn't mean threads are faster, it really just means Window's CreateProcess()+setjmp()+longjmp() slower and uglier than fork().

        Windows threads and pthreads are functionally equivalent, and for some metrics in some circumstances, the actual implementations might be better at some tasks versus others. In general, a program written for pthread

        • Re:Eeew, threads. (Score:5, Interesting)

          by Mysticalfruit ( 533341 ) on Monday February 26, 2007 @01:03PM (#18155636) Homepage Journal
          A while back I had to write a server that would recieve concurrent network connections from different clients and then get some data from those clients and do some processing and then interact with a database, then when it's done the fork exits.

          I ended up writing the whole thing using forks and no pthreads. My code was then subjected to a code review and one of the questions that came up in the review meeting was why I used fork and didn't do the implementation in pthreads. My arguement was one of complexity. I was challenged with the "fork is old technology, you should have used pthreads" and my response was "My implementation is easy to understand, oh and by the way, it works!"

          Needless to say, my code has been in production for about a year and a half with no issues. I'm sure someone smarter than me could have wrote the whole using pthreads, but I'm just not sure what it would have gained them other than a slightly smaller memory footprint but at the price of increased complexity.
          • Re:Eeew, threads. (Score:4, Informative)

            by Kashif Shaikh ( 575991 ) on Monday February 26, 2007 @02:29PM (#18157108)
            You had no issues because a) performance was good enough and b) the rate of incoming client requests was relatively small compared to a loaded webserver. Now if you had thousands of client requests-per-second, the fork will show why-you-should-not-use-it-in-such-situations. In such cases you can use a pool of forked processes or simply write the whole damn thing using threads. For example, apache gives you the ability to change 'worker' modules...and you can experiment with that to get an idea of all these request processors. btw, threads don't complicate your code as long as you minimize data-sharing between threads and write the thread the same way as you were writing a forked process, except that you put all global variables within the thread's local data area. Kashif
          • If you don't touch the heap, then not much is gained from pthreads over fork() in terms of memory usage. Code segments are shared, data is copy on write, and the stack is not shared in either case.
        • Re: (Score:3, Informative)

          by pthisis ( 27352 )
          Windows does have a copy-on-write process creation mechanism--use ZwCreateProcess or NtCreateProcess with a NULL SectionHandle. It wasn't in Win98 and earlier, and it's poorly documented, which means a lot of Windows programmers don't use it and threads get massively overused.

          But threads are rarely the right choice; OS developers spent years implementing protected memory for good reasons, and throwing it out even within the bounds of one process is rarely beneficial. If you need to share a ton of complex d
      • Re:Eeew, threads. (Score:5, Informative)

        by pthisis ( 27352 ) on Monday February 26, 2007 @06:05PM (#18160094) Homepage Journal

        I don't know why the Windows equivalent of fork() is slower than the Unix fork(). Perhaps it is a historical thing. Unix programs often use fork() - shell scripts use it all the time (this is one reason why a Python or Perl script is often faster). I'm just guessing now, but perhaps Unix fork() is efficient because it is frequently used and has therefore been optimised in various ways (e.g. memory is only copied if there is a write on Linux).


        I already got modded down for mentioning it elsethread (not sure why), but Windows does have ZwCreateProcess and NtCreateProcess. Both of those will do a copy-on-write fork() style process creation if you pass them a NULL SectionHandle--it is much more efficient than the normal CreateProcessEx and is the way to go for doing heavy multiprocess stuff on Win32.

        see, e.g., http://www.osronline.com/showThread.cfm?link=35916 [osronline.com]
    • Re:Eeew, threads. (Score:5, Insightful)

      by daVinci1980 ( 73174 ) on Monday February 26, 2007 @10:52AM (#18153512) Homepage
      These solutions are not equivalent. And the reason that fork/exec doesn't have the same problems as threading is because it can only (realistically) solve a subset of the problems that multithreading can solve.

      You have to consider the task you're working on before you decide whether you want to go with fork/exec or multiple threads.

      A sibling post mentioned the cost of creating new processes on windows, and that's definitely something to consider: it's quite expensive to do so on windows.

      However, the more important question is the problem you're working on solving.

      If you're working on a task that allows each drone to work without communicating with any of the other drones, then fork/exec is a possible candidate. If you're working on an application where you require even a minimal amount of synchronization between different drones, fork/exec is a huge, huge pain in the ass.

      An example of a good fork/exec app: webserver. One process deals with hearing the incoming connection, spawns off a new process to actually handle an individual connection. As a bonus, a single bad client connection will most likely NOT kill the whole webserver. (A malicious client will kill the process they've connected to, but probably none of the other processes, unless they manage to hang a database, etc).

      An example of a good multithreaded app: anything that plays lots of sounds (for a specific example, a game). There's lots of synchronization that has to go on here: threads have to be started (or more likely pulled from a pool) to play a sound, the threads playing the sound have to check back periodically to see if they should stop playing (or need to adjust their volume or other processing effects), they need to notify the originating thread when they have completed, etc. No one in their right mind would use fork/exec for this. Besides the high overhead of the process spawn on windows, you would need a process for each of the sounds playing, and you would need to use the OS interprocess communication apis to synchronize between the different processes (shared memory, global mutexes, or file pipes). Note that file pipes aren't sufficient for synchronization, so you'd still have to use OS mutexes to sync on.

      Yup.
    • Re: (Score:3, Insightful)

      by Jonny_eh ( 765306 )
      Just an FYI, fork isn't always available. The best example I can think of is uClinux, a linux distro for embedded computers. With an MMU, a process cannot be copied, therefore, only threads can be used. This can be a pain in the butt sometimes, but luckily pthreads aren't so bad once you know how to avoid races and deadlocks.
    • MSFT POSIX (Score:3, Interesting)

      Here's the one thing Windows needs: fork()

      Windows has fork(), as well as all the other POSIX calls.

      Originally, Windows NT had 4 separate APIs: the NT API, Win32, POSIX, and OS/2. The NT API was (and still is) the one used by the kernel. It has all the capabilities necessary to support the other three, and is never (well, rarely at least) used directly by applications. Win32 was, at the time, very new and hadn't seen wide use--it was designed as the primary API for Windows 95, and Microsoft wasn't yet su

  • by musikit ( 716987 ) on Monday February 26, 2007 @10:11AM (#18153006)
    i have had to do a lot of porting from win32 to linux/bsd/mac lately and maybe i just cant find it in the documentation anywhere but 1 function i would really appreciate the pthread team adding is

    pthread_join_with_timeout() the equivilent of the win32 WaitForSingleObject

    often i set a flag for a thread to end and it might have already been completed. i want to be able to join immediately if it's already completed and if it isn't process some other event and try to join again.

    i can program around this however it would be extremely nice addition to pthreads.
    • Re: (Score:2, Insightful)

      by Steendor ( 917855 )

      Obviously it's not a required featuer, but perhaps it just wasn't deemed to be a useful feature.

      The few times I've written multi-threaded programs, I had no reason to join completed threads at the earliest possible moment. One use I can think of would be to recycle threads to process a queue. In that case, wouldn't it be better to divide the recycling management and the processing into separate threads?

    • by tjw ( 27390 ) on Monday February 26, 2007 @10:35AM (#18153280) Homepage

      I'm not an expert on pthreads by any means, but I think what you're looking for is pthread_cond_timedwait().
      • by dominator ( 61418 ) on Monday February 26, 2007 @12:05PM (#18154616) Homepage
        pthread_cond_timedwait() waits on a condition variable, which basically signals that a mutex has been released. Win32 calls these things "events". It is not the same thing as joining on a thread. Joining a thread means "I'm waiting for this thread to exit, so that I can capture its return value."

        Sure, you could implement something like pthread_join_with_timeout() using a conditional inside the thread. But you'd need to do that manually, as pthreads doesn't provide a primitive for that particular use-case AFAIK.
        • Re: (Score:3, Informative)

          by boa ( 96754 )
          >Sure, you could implement something like pthread_join_with_timeout() using a conditional inside the thread. But you'd need to do that manually, as
          > pthreads doesn't provide a primitive for that particular use-case AFAIK.

          A quick look in pthread.h tells me that there's one function named pthread_timedjoin_np. The function seems to be a GNU extension and the _np suffix is short for not portable. It probably does that the OP wants, but may not be portable enough for his needs.

          HTH
          boa
    • by awol ( 98751 )
      Yeah, I know the feeling. We have an abstraction layer that does this goodness although even then not generically. The tradeoff in my view is true shared memory, and the pain that comes from the absence of that in Windows probably outweighs the goodness of WaitForSingleObject.

      Interestingly, Linux has a call; semtimedop which works for semaphores
  • PThreads is better (Score:5, Informative)

    by swm ( 171547 ) <swmcd@world.std.com> on Monday February 26, 2007 @10:19AM (#18153086) Homepage
    The articles read like one of those English assignments where you have to pick an issue and then write two essays, one supporting each side. Probably the author wrote them to generate traffic to his websites, or maybe for freelance fees.

    Anyway, PThreads is better. The reason is that Win32 gives you a fixed set of synchronization primitives. If you can solve your problem with those primitives. they work great. If you can't, you are completely stuck.

    For example, it used to be that a socket handle was not a synchronization object, so you couldn't integrate select() calls with other synchronization primitives. Maybe that's been fixed, but if it isn't sockets, it will be something else.

    PThreads gives you condition variables. They are harder to program, but once you understand them, you can use them to synchronize on absolutely anything. You aren't dependent on the OS to have foreseen your special needs and provided special synchronization primitives to meet them.

    If you really want the Win32 model, it is easy enough to build it on top of PThreads, but there is no way to build PThreads on top of Win32.

    The complaint about lost signals in PThreads means that the author is using them incorrectly.
    • by leuk_he ( 194174 ) on Monday February 26, 2007 @10:33AM (#18153252) Homepage Journal
      there is a pthreads [sourceware.org] implementation build on top if win32. I am not saying it is efficient, but it does the job.
    • Re: (Score:3, Interesting)

      by complexmath ( 449417 ) *
      If you really want the Win32 model, it is easy enough to build it on top of PThreads, but there is no way to build PThreads on top of Win32.

      Not strictly true. It is possible to build condition variables for Windows (Windows has Semaphores after all, which can be used to make just about anything), but the Windows threading model makes doing so far from easy. Please note that I'm not defending WinThreads, however, so much as clarifying this particular issue.
    • by PhrostyMcByte ( 589271 ) <phrosty@gmail.com> on Monday February 26, 2007 @10:36AM (#18153294) Homepage
      You're in luck-

      Vista comes with APIs for condition variables and reader-writer locks so you don't have to spend 15 minutes writing your own.
    • Re: (Score:3, Interesting)

      by fitten ( 521191 )
      I've programmed in both and, other than the fact that you can't use sockets in the Wait... APIs (as you mention - but the BSD socket code is layered on top of native Win32, so you'd be passing objects created by two different subsystems to one subsystem's call, which shouldn't be expected to work), the rest of your post is either lack of experience with Win32 threads or subjective preference on your part.

      Personally, I've found situations using each API where the functionality desired was very difficult to r
    • You can do the same things with both of them, but Win32 threads are less of a pain in the ass to work with.
    • by dmayle ( 200765 ) on Monday February 26, 2007 @11:01AM (#18153630) Homepage Journal

      It's not so cut and dry. I use a library I wrote to abstract away PThreads and Win32 Threads to give me a multi-platform interface, but I would say that each side has their upsides and downsides.

      With pthreads, there's no way to combine socket i/o and thread notification. In Win32, I can have a thread waiting on both a socket and an event at the same time, allowing me to cleanly signal I/O blocked threads. This isn't the case with pthreads.

      However, Win32 REALLY needs a way to handle negative mutexes (ie. taking more than one resource from a mutex at a time). I had to write my own, and it was a serious pain to make sure I didn't have any race conditions. All the articles I've seen on Win32 equivalents had race conditions, and that means that there means that there are probably developers trusting multi-threading primitives that they really shouldn't be./p>

      • Re: (Score:3, Informative)

        by dmayle ( 200765 )

        As my comment is mounting in score, I just realized that I said negative mutexes when I meant negative semaphores. Of course you can't have a negative mutex, a mutex is just for mutual exclusion. It's a semaphore that has a count associated with it.

        Sorry for the typo...

    • by Twylite ( 234238 ) <twylite.crypt@co@za> on Monday February 26, 2007 @11:23AM (#18153904) Homepage

      You are talking mostly bollocks, probably because you don't program using the Windows API

      Anyway, PThreads is better. The reason is that Win32 gives you a fixed set of synchronization primitives. If you can solve your problem with those primitives. they work great. If you can't, you are completely stuck.

      And PThreads also gives you a fixed set of primitives. In some respects they are more powerful, in others they are weaker. This is a bullshit strawman.

      For example, it used to be that a socket handle was not a synchronization object, so you couldn't integrate select() calls with other synchronization primitives.

      WTF?

      1. select() has nothing to do with synchronization. Although it does have something to do with scheduling.
      2. select() can't wait on "synchronization primitives" under *nix. Really. Try man select [man.cx]. It works with FDs, only.
      3. select() is not a core function of the Windows API. It is part of Winsock, which uses lower level scheduling primitives.
      4. Finally, if you want to do asynchronous development with Windows you use Async IO, not select. Async IO is built on top of Events, which are synchronization primitives.

      That brings me to the next point: in Unix there is no wait to wait on multiple synchronization primitives (as opposed to FDs) at once, and only a few primitives support a timed wait. In Windows you have WaitForMultipleObjectsEx [microsoft.com]. Look it up.

      Let me be clear on the difference: in Windows the scheduler API for waiting on IO and synchronization primitives is fully integrated - you can wait on any combination of IO and sync objects in the same Wait call. You must of course be using Windows Async IO which uses Events rather than FDs as the waitable object. Under *nix you can wait for multiple condition variables, or multiple file descriptors, or a single mutex / thread / process. There is no way to link an FD to a condition variable.

      PThreads gives you condition variables. They are harder to program, but once you understand them, you can use them to synchronize on absolutely anything. You aren't dependent on the OS to have foreseen your special needs and provided special synchronization primitives to meet them.

      In Windows you have Mutexes, Events and Semaphores. Events alone are sufficient to provide almost identical functionality to condition variables. You may have missed that memo.

      I say "almost identical" because the underlying scheduler behaviour is slightly different, which makes it very difficult to perfectly emulate Pthreads on Win32. Read Strategies for Implementing POSIX Condition Variables on Win32 [wustl.edu].

      If you really want the Win32 model, it is easy enough to build it on top of PThreads, but there is no way to build PThreads on top of Win32.

      Cough. Bullshit. Cough. Read Porting of Win32 API WaitFor to Solaris Platform [sun.com] to get a clue. It is possible to build Pthreads on top of Win32, and vice versa. Neither emulation is particularly efficient though.

      The complaint about lost signals in PThreads means that the author is using them incorrectly.

      The complaint about weakness in the Win32 scheduling API means that the author is using it incorrectly.

  • It's not that difficult. POSIX' value is in its portability. Win32's value is in the fact that it's the native model.

    Generally speaking, the native model will always offer superior performance and a superset of the features of POSIX threads. Be that Win32, Solaris, Linux, or what have you -- it's a good rule of thumb that the native threading model and API performs better and is more flexible.

    That said, the difference is generally small enough that it's eclipsed by the portability feature if portability wil
  • If you keep the two articles next to each other, you get a nice comparison of the advantages and disadvantages of each approach. Pthreads are apparently more elegant and easier to understand, but also more strict, while win32 threads are more lenient when you're not quite sure what's going on. In pthreads, there's only one way to start as new thread, in win32 there's more than one way. Undoubtedly each with its own advantages, but you do have to know the difference. As for persistence of signals, there's ap
    • by geekoid ( 135745 )
      The articles in question are 3 years apart. Things change in 3 years.

      Port? aha. I have had to write code that can be compiled in either enviroment.
      Same code. Actually it had to cimpile in Solaris, Linux and Win32.

    • If you don't have a handle on the state machine, don't go further and hope that child processes through a fork or a thread spawn are going to inherit the conditions you want. This is a weak argument for spawning Win32 threads.

      When compiling, the actions taken to get to assembler/machine code are far different between Win and Posix. Posix has a wonderful elegance and a brevity of code, but Win will take a much larger portion of the libs (depending on whose compiler you're using) to ensure it catches the stat
  • I bet that "anonymous reader" is actually Clay Breshears himself.
  • What will net the most /. hits?
    • by caluml ( 551744 )
      If thee casteth two opposing nets, thee will catcheth at least some fish.

      - Me, 2007.
  • by 0xdeadbeef ( 28836 ) on Monday February 26, 2007 @10:29AM (#18153208) Homepage Journal
    One uses lowercase and underscores. The other uses studlycaps and Hungarian notation. It is an aesthetic choice.
  • I don't know how win32 threads work, but I do know that I would like my thread system to have an interface like fork(), so both the original and the new thread continue from that point onward. This would unify threads with continuations, allowing interesting and powerful programming techniques. POSIX threads don't work that way, but Linux's clone() can, or so the manpage leads me to believe.
    • If you can re-write your forkish program from the form

      while()
      if (!fork())
      {
      blah;
      blah;
      blah;
      }

      to

      doWork(args)
      {
      blah;
      blah;
      blah;
      }

      while()
      if (!fork())
      doWork(args);

      Then you can do what you want with a wrapper oriented around pthread_create() and friends so that your code will look like

      while()
      magicFunc(doWork, args)

      with trivial complexity.

  • by radarsat1 ( 786772 ) on Monday February 26, 2007 @10:30AM (#18153216) Homepage
    The thing is, they are just APIs. They both do just about the same thing. Asking which one is better is a pretty pointless question. I have always thought that the WaitFor* functions in Windows are quite nice, but frankly not that much of an advantage. It's quite rare that you actually need to wait for multiple objects of different types at the same time. Combine that with the fact that its semantics are slightly different for different objects (it destroys a thread, but only unlocks a mutex), and your program is that much more difficult to read. Of course, this is just comparing two APIs, a mostly pointless exercise, and says _nothing_ about implementation, which is quite a bit more important in terms of comparison. For example, Linux has completely changed its pthreads implementation since the switch from 2.4 to 2.6 (from LinuxThreads to NPTL), and programmers get the advantages without needing to change anything. In Windows, of course, we have no (or very little) idea of the implementation, except for what we can infer from the API, and performance tests. A third argument in this little debate could be to argue that one should just stay away from threads, period. I haven't successfully done it myself, since I find the threading paradigm useful, but using processes and non-blocking IO properly, one can avoid threads completely. Of course that's a bit easier to do with some of the Posix functions (eg. socketpair). But doing so will probably result in a more robust piece of software, and which scales better to multiple cores/processors. (Because processes do not share memory, so inter-thread cache misses will be minimized.)

    That said, I find it quite creepy that this guy wrote these two articles with extremely similar wording for his introductions, making the exact opposite points. It is very strange. I wonder what his motivation was.
  • Is this a joke ? (Score:4, Informative)

    by CmdrGravy ( 645153 ) on Monday February 26, 2007 @10:31AM (#18153222) Homepage
    Is this some kind of weird joke ?

    First of all on it's own terms the story makes no sense, the anonymous coward starts off by saying it's interesting when people disagree. He then links to two articles which, as he points out, are written by the same person and then asks who is right. He has just pointed out the opinions are both from the same person and he wants to know who is right, this is just moronic.

    Secondly although I know nothing about PThreads or Win threads I can see that both those articles are largely the same with just the terms PThreads and Win threads switched so in one article he is claiming an advantage for one based on what he has stated as the advantages of the other in his other article.

    Why is this on the front page, why was the submission accepted in the first place when it's complete nonsense and the most recent post by the author of both articles was in 2006.
  • Like the author, I have programmed with both pthreads and the Win32 threading API. I like the design of the pthreads API better, but (as the author also points out), pthreads has no equivalent to WaitForMultipleObjects. Sometimes it is very convenient to be able to wait on many objects and be able to be signaled by any one of them. With pthreads there is no way to do this.

    Or am I missing something? Please someone, tell me how to wait on multiple objects (and be triggered by just one) with pthreads!
    • by Cheesey ( 70139 )
      Couldn't you use a semaphore for that? Get your producers to call sem_post when ready, and have your consumer call sem_wait. sem_wait will block until a producer calls sem_post. The relationship between calls to sem_post and calls to sem_wait is guaranteed to be 1:1.

      Did I misunderstand what you were trying to do?
    • Re: (Score:3, Insightful)

      by swm ( 171547 )
      Let's see if I remember how to do this...

      mutex mx;
      condition_variable cv;
      int a, b, c, d;

      ----- one thread -----

      lock(mx);
      while (! (a || b || c || d)) wait(mx, cv);
      unlock(mx);

      ----- another thread ------

      lock(mx);
      a = 1;
      signal(cv);
      unlock(mx);

      ----- another thread ------

      lock(mx);
      b = 1;
      signal(cv);
      unlock(mx);

  • AFAIR the windows theading model is better, because windows was designed with heavily multithreading in mind, and a very expensive operation of creation of new processes.

    In Linux is the other way around: forking a process is very efficient, so no one used threads so they were not as efficient as the ones in Windows.

    Of course both process creation in Windows and threading in Linux could have been perfected in all this years, but that is something I don't know.

    That said, a bug in a thread will bring the appli
  • by NullProg ( 70833 ) on Monday February 26, 2007 @10:47AM (#18153440) Homepage Journal
    It sounds like the developer from Intel needs to ask IBM:

    http://www-128.ibm.com/developerworks/linux/librar y/l-ipc2lin1.html [ibm.com]

    Enjoy,
  • Engineer discovers that there are pros and cons in deciding between two systems, but has to make a general value judgment. The world does not obey trichotomy [wolfram.com], you know.
  • by edwinolson ( 116413 ) on Monday February 26, 2007 @10:55AM (#18153550) Homepage
    I seem to recall looking for--and not finding-- a win32 equivalent of pthread's condition variables. E.g., atomically release a mutex and then wait for an event. As the (excellent) pthread man page describes, this is a useful operation, often necessary to avoid a race condition.

    What is the right way to do a pthread_cond_wait under win32?

  • wdiff output (Score:4, Informative)

    by cortana ( 588495 ) <sam AT robots DOT org DOT uk> on Monday February 26, 2007 @12:27PM (#18155010) Homepage
    Why [-Pthreads-] {+Windows Threads+} are better than [-Win32 threads-] {+POSIX Threads+}
    Clay Breshears
    [-2006-10-19-]
    {+2003-05-13+}

    I've used both POSIX threads (Pthreads) and [-Win32-] {+Windows+} threads [-APIs-] {+APIs,+} and I believe that [-Pthreads-] {+Windows+} has the better programming model of the two. While each threading method can create threads, destroy threads, and coordinate interactions between threads, the reason I make this claim is the simplicity of use and elegance of design of [-Pthreads.-] {+the Windows threads API. This is all from the perspective of multithreaded code developers or maintainers.+} Let me illustrate with a few examples.

    [-Separate-] {+Simplicity of+} data types. In Pthreads, each object has its own data type [-while-] {+(pthread_t, pthread_mutex_t, pthread_cond_t, etc.) while,+} in [-Win32 threads-] {+Windows threads,+} there is [-a mix of handles and separate types.-] {+pretty much just the one type: HANDLE.+} For Pthreads this means different functions are used for working with each object type. Reading and understanding Pthreads code written by someone else [-is straightforward-] {+can be straightforward. However, this does mean that the programmer must know the number, order,+} and [-less apt to lead to confusion.-] {+type of parameters for all the different functions.+} On the other hand, because of the use of the same type for different objects, [-when-] {+there is+} a [-Win32 program uses WaitForSingleObject, it may not-] {+Create* function for each different object and a corresponding Release* function for most.

    Perhaps the biggest advantage of a single object data type is that there is only the one function needed to make a thread block while waiting for an object: WaitForSingleObject. Thus, only one set of parameters needs to+} be {+known regardless of whether the code is waiting on a thread, a mutex, a semaphore, or an event. The related function, WaitForMultipleObjects, is just as simple to use and easily overcomes the problem of needing to wait for multiple thread terminations one function call at a time (pthread_join) that Pthreads requires. While some may say that using a single data type for many different objects can lead to confusion when used in WaitFor* calls, programmers should set the name of the handle such that it is+} readily apparent [-if-] {+whether+} the code is expecting a thread termination, an event to be signaled, or a mutex to be released. [-This also illustrates my next point.

    Unambiguous-] {+WaitForMultipleObjects+} functionality. [-I've-] {+Besides being able to block a thread waiting for multiple thread terminations in a single call, the programmer can+} actually [-seen Win32-] {+wait for any out of a set of threads to terminate. That is, even when only one thread has completed, the WaitForMultipleObjects function can be set to return and indicate which thread triggered the return. If there is specific "clean up" processing that depends on the identity of the thread that finished, this can be done before returning to wait on the remaining threads. This clean up processing will be done in the most efficient order possible, soon after each thread terminates, no matter in what order this happens. Pthreads can perform similar post-processing, but will need to wait for the threads to terminate is some fixed order. So, even if the last thread finishes first, it must wait for all the post-processing of the previous threads to be completed.

    Because different objects all use the HANDLE type, a call to WaitForMultipleObjects can be set to wait for any combination of threads, mutexes, semaphores, and/or events. This feature can give the programmer a flexibility that cannot be easily (if at all) duplicated in Pthreads. As an example, I've written Windows+} code that used an array to hold both thread and [-mutex handles, then wait on those-] {+event+} handles {+to support a threaded search through data. The ideas was to signal the blocking thread if the item being looked for was found+} and [-execute differen
  • by trainsnpep ( 608418 ) <mikebenza@gm[ ].com ['ail' in gap]> on Monday February 26, 2007 @01:37PM (#18156196)

    We have always been at war with Pthreads. We have never been at war with Windows threads.

    The submitter is clearly nuts. Everyone knows that we have always been at war with Windows threads. Anyone who suggests we're at war with Pthreads is insane.

A sheet of paper is an ink-lined plane. -- Willard Espy, "An Almanac of Words at Play"

Working...