Posix threads problem

后端 未结 6 921
暗喜
暗喜 2021-01-17 02:12

I am trying to understand pthreads by example. I have made the following code that is giving different answers everytime I run! Could anyone explain the bug please? TIA, Svi

相关标签:
6条回答
  • 2021-01-17 02:22

    I realize this post is old, but, alternatively, you may use a pthread_exit() at the end of main() so that main() will wait for all its peer threads to finish before exiting prematurely.

    0 讨论(0)
  • 2021-01-17 02:22

    Ok, finally added the extracode as suggested by the experts and it works fine now. Thanks again to all. :)

    for ( t = 0; t < NUM_THREADS; t++ ) {
        (void) pthread_join(threads[t], NULL);
    }
    
    0 讨论(0)
  • 2021-01-17 02:33

    There is no bug, this is just how threads work. Your main thread creates new threads, which are at that point "ready to run". At some point in time (determined by the OS), your main thread will be suspended and one of the other threads will run for a certain amount of time (usually a few tens of milliseconds). The system will keep switching between threads while there exist running threads for your program.

    The exact point in time when your main thread will be interrupted and one of the other threads can print it's Hello World will depend on what the OS scheduler decides, based on how long your main thread is already running, other activity in the system, external (I/O) events, etc.

    EDIT to include my comment below:

    The reason why you're seeing 3, then 4, then only 2 "Hello Worlds", is that you created the threads, but you didn't wait for them to actually get scheduled and run. When your main loop ends, the program is dead, irrespective whether your other threads have had a chance to run. If you want all of your threads to be finished, you need to do a pthread_join on each of your threads before returning from main.

    0 讨论(0)
  • 2021-01-17 02:35

    If you mean the order of the answers, yes, it will be different since which thread runs is decided by the Linux scheduler.

    To elaborate: Once you create your threads, the order in which they get CPU time depends on the underlying OS scheduler(here, Linux scheduler). This may not be the same everytime.

    0 讨论(0)
  • 2021-01-17 02:37

    I agree with the other two answers.
    It may also be worth noting that the process exits immediately after the creation of the threads. It will create all 4, but each may not have time enough to do anything before the program exits.

    0 讨论(0)
  • 2021-01-17 02:43

    The reason you don't see the other threads executing, as per your comments to the other answers is because your main() function (and hence your program) returns before the other threads have had an opportunity to execute. If you put a sleep(5) before your main() returns, you will see them execute.

    0 讨论(0)
提交回复
热议问题