在pthread_join()中阻塞 [英] Blocking in pthread_join()

查看:598
本文介绍了在pthread_join()中阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据手册页:

pthread_join()函数应中止调用的执行 线程,直到目标线程终止,除非目标线程 已经终止.

据我所知,调用过程将一直阻塞,直到指定的线程退出为止.

现在考虑以下代码:

pthread_t thrs[NUMTHREADS];

for (int i = 0; i < NUMTHREADS; i++)
{
    pthread_create(&thrs[i], NULL, thread_main, NULL);
}

pthread_join(thrs[0], NULL); /* will be blocked here */
pthread_join(thrs[1], NULL);
pthread_join(thrs[2], NULL);
/* ... */
pthread_join(thrs[NUMTHREADS - 1], NULL);

pthread_join(thrs[0], NULL)的调用中,调用线程将被阻塞,直到thrs[0]以某种方式退出.但是,如果另一个线程(例如thrs[2])在调用pthread_join(thrs[0], NULL)时被阻塞而又调用pthread_exit()怎么办?为了接收thrs[2]的返回值,我们是否必须等待thrs[0]退出?

解决方案

是的-在thrs[[0]thrs[1]也退出之前,在thrs[0]上阻塞的主线程将不会从thrs[2]获取结果. /p>

如果需要更大的灵活性,一个选择是做一些事情,例如让线程将结果发布到队列中,或者以其他方式发出需要加入线程的信号.主线程可以监视该队列/信号并获得必要的结果(可能来自pthread_join(),该结果是在已知从队列/信号中获取的信息完成的线程上完成的).

According to the manual page:

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

So, as I understand, the calling process will block until the specified thread exit.

Now consider the following code:

pthread_t thrs[NUMTHREADS];

for (int i = 0; i < NUMTHREADS; i++)
{
    pthread_create(&thrs[i], NULL, thread_main, NULL);
}

pthread_join(thrs[0], NULL); /* will be blocked here */
pthread_join(thrs[1], NULL);
pthread_join(thrs[2], NULL);
/* ... */
pthread_join(thrs[NUMTHREADS - 1], NULL);

The calling thread will be blocked in the call to pthread_join(thrs[0], NULL), until thrs[0] exit in some way. But how if another thread, for example, thrs[2] call pthread_exit() while we are blocked in the call to pthread_join(thrs[0], NULL)? Do we have to wait for thrs[0] to exit in order to receive the return value of thrs[2]?

解决方案

Yes - the main thread blocked on thrs[0] will not get the result from thrs[2] until after thrs[[0] and thrs[1] have also exited.

If you need more flexibility one option is to do something like having the threads post their results in a queue or signal in some other way that the thread needs to be joined. The main thread can monitor that queue/signal and get the necessary results (which could come from a pthread_join() that is done on the thread that is known to be completed from information int he queue/signal).

这篇关于在pthread_join()中阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆