开发者

Will pthread_join halt the parent program if the child thread is still working?.. Will pthread_detach make it faster?? instead of using join?

My program is something like this.. I wanted to know will I make开发者_JAVA技巧 my program slow, if I call pthread join???

void* a(void *a)
{
 do---something();//which is a very long procedure, I mean takes a lot of time...
 pthread_exit();
}

main()
{
 while(1)
 {
  pthread_create(a);
  pthread_join(a);
 }
}

So, if I call pthread_join, will I halt at that point until the child thread finishes it execution, or do I go on and create one more thread ?????


From the POSIX spec:

The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated.

If this is not what you want, either defer the call to pthread_join (putting all of the pthread_t's in a container so you can join them later) or use pthread_detach so you do not need to join them at all.


pthread_join() blocks until the child thread has exited, but you still want/need to call it in order for the child thread to be cleaned up properly once it has gone away. But as you say you don't want to have your main thread blocked, so how to deal with this? The way I would do it is to have the child thread send a message (via socket-pair or some other mechanism) back to its parent thread just before it exits.... when the parent thread receives this message, then it knows that now is a good time to call pthread_join(), since the child thread is already gone (or almost gone) and therefore pthread_join will never block (or at least not for more than a few milliseconds).


the join call blocks until the thread exits


You probably want to use non-blocking sockets to handle many clients without having to create a thread for each. See often quoted The C10K problem for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜