Order of running threads in pthreads

2019-03-03 07:29发布

In the following program, what are the possibilities for the ordering of threads? Assuming "function" will print thread id which is unique (since here we have only one process). I always get the order th1,th2!

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
int main()
{
            pthread_t th1;
            pthread_t th2;
            pthread_create(&th1, NULL, function, NULL);
            pthread_create(&th2, NULL, function, NULL);
            pthread_join(th1, NULL);
            pthread_join(th2, NULL);
}

   return 0;
}

4条回答
祖国的老花朵
2楼-- · 2019-03-03 08:15

The only ordering guarantees here are that pthread_join(th1, NULL); will not return until thread 1 has exited and pthread_join(th2, NULL); will not return until thread 2 has exited. Consequently, the main() function will not return (and the process will not exit) until both thread 1 and thread 2 have exited.

There is no ordering imposed between thread 1 and thread 2 - their execution can be arbitrarily interleaved.

查看更多
Viruses.
3楼-- · 2019-03-03 08:15

I don't think there will be any specific ordering. Threads on the modern machines are executed in parallel and its not deterministic which thread's print statements will get executed first !

The only ordering constraint that can be assumed is that thread 2 will come before thread 1 because of second pthread_join

查看更多
别忘想泡老子
4楼-- · 2019-03-03 08:16

The start tell the OS "start doing this". The joins say "wait until this is done".

Now you are telling the OS "do this" and "do this". The OS can pick any order. But most of the time it will just do it in the order you told it to.

It's like ordering two sammies at subways. 99% of the time you'll get them made in the same order you asked for them. But every blue moon, you won't. But you are still waiting for both of them before you pay :)

查看更多
该账号已被封号
5楼-- · 2019-03-03 08:17

It is like a factory. Got two workers. One needs a bit of coffee and therefore starts a little later at the same task as the other one (well takes time for the kettle). Then that worker is firing on all cylinders but the coffee takes effect. Needs to use the loo. So the one that started earlier finished first but spent more time working. If only that worker had a bucket?!

查看更多
登录 后发表回答