如何确定哪个线程已完成
How to determine which thread is done
我有一个调用pthread_join
但循环的顺序与线程终止的顺序不匹配。如何监视线程完成然后调用 join?
for ( int th=0; th<sections; th++ )
{
cout<<"start joining "<<th<<endl<<flush;
result_code = pthread_join( threads[th] , (void**)&status);
cout<<th<<" join error "<<strerror(result_code)<<endl<<flush;
cout<<"Join status is "<<status<<endl<<flush;
}
这是我的解决方案,它似乎通过服务第一个来最大化多线程吞吐量完成线程 .此解决方案不依赖于循环顺序pthread_join。
// loop & wait for the first done thread
std::bitset<Nsections> ready;
std::bitset<Nsections> done;
ready.reset();
for (unsigned b=0; b<sections; b++) ready.flip(b);
done = ready;
unsigned currIdx = 1;
int th = 0;
int th_= 0;
int stat;
while ( done.any() )
{
// main loops waiting for 1st thread to complete.
// completion is checked by global vector
// vStatus (singlton write protected)
// and not by pthread_exit returned value,
// in ordder to maximize throughput by
// post processig the first
// finished thread.
if ( (obj.vStatus).empty() ) { Sleep (5); continue; }
while ( ready.any() )
{
if ( sections == 1 ) break;
if ( !(obj.vStatus).empty() )
{
if ( currIdx <= (obj.vStatus).size() )
{
th_ = currIdx-1;
std::string s =
ready.to_string<char,std::string::traits_type,std::string::allocator_type>();
cout<<"checking "<<th_<<"t"<<s<<"t"
<<(ready.test(th_)?"T":"F")<<"t"<<(obj.vStatus)[th_].retVal <<endl;
if ((obj.vStatus)[th_].retVal < 1)
{
if (ready.test(th_))
{
th=th_;
ready.reset(th);
goto retry;
}
}
}
}
Sleep (2);
} // while ready
retry:
cout<<"start joining "<<th<<endl<<flush;
result_code = pthread_join( threads[th] , (void**)&status);
switch (result_code)
{
case EDEADLK: goto retry; break;
case EINVAL:
case ESRCH:
case 0:
currIdx++;
stat = status->retVal;
free (status);
done.reset(th);
std::string s =
done.to_string<char,std::string::traits_type,std::string::allocator_type>();
cout<<"joined thread "<<th<<"t"<<s<<"t"
<<(done.test(th)?"T":"F")<<"t"<<stat <<endl;
while (true)
{
auto ret=pthread_cancel ( threads[th] ) ;
if (ret == ESRCH) { netTH--; break; }
Sleep (20);
}
break;
}
如何监视线程完成然后调用 join?
通过让联接检测完成。(即不做任何特别的事情(
我有一个调用pthread_join的循环,但循环的顺序与线程终止的顺序不匹配。
循环的顺序无关紧要。
a( thread[main]
呼叫thread[1].'join'
将被暂停,直到thread[1]
退出。 之后,线程 [main] 将被允许继续循环的其余部分。
b( 当thread[2]
在thread[1]
之前终止时,thread[main]
调用thread[2].join
会立即返回。同样,thread[main]
继续。
c( 确保thread[1]
在thread[2]
之前终止(以匹配循环序列(是一项令人惊讶的耗时工作,没有任何好处。
更新正在进行中...寻找我认为我已经提交的代码。
相关文章:
- C++一个线程如何正确通信其任务已完成?
- 从矢量中删除已完成的线程
- 在std::线程中使用已分配的结构数据
- future::wait() 是否与 async() 执行线程的完成同步?
- 如何确定哪个线程已完成
- OpenMP 是否将已完成部分的线程重用到另一个线程?
- C++线程在完成执行后仍然"可连接()"?
- 如何知道分离的STD ::线程是否完成了执行
- 判断哪些线程已终止的有效方法
- 线程已退出,代码为 1:Join() 和 Detach()
- 多线程 – 已知的相似性解决方案
- 主线程关闭,而工作线程未完成
- 通知调用方线程已完成
- 已完成线程使用的可用资源
- c++应用程序的登录应该在单独的线程中完成吗
- 确保线程已启动winapi c++
- std::mutex 与 RAII 但在后台线程中完成和发布
- 在已完成的std::线程连接上发生死锁
- 如果由于接收对象的线程已结束而未处理Qt信号,参数会被删除吗?
- 表示一批线程已完成主线程