【发布时间】:2017-05-18 14:23:49
【问题描述】:
我的项目有问题。 它向我抛出错误代码 3。
我只是添加了我的部分代码,让你看看我做了什么。 在 main.cpp 我在线程上声明然后我发送到 initRequestThreads(in thread.h) 以创建线程。然后在 main.cpp 我让主进程等待它。
main.cpp
pthread_t *requestersThreads = new pthread_t[Length_Tasks];
requestsPool->initRequestThreads(&requestersThreads);
void* status;
// wait for all requests threads
for(t=0; t<Length_Tasks; t++) {
rc = pthread_join(requestersThreads[t], &status);
if (rc) {
cout<<"ERROR; return code from pthread_join() is "<< rc <<endl;
exit(-1);
}
cout<<"Main: completed join with REQUEST thread " << t <<" having a status of "<<(long)status<<endl;
}
// wait for all resolvers threads
for(t=0; t<resolveThreadsAmount; t++) {
rc = pthread_join(reoslveThreads[t], &status);
if (rc) {
cout<<"ERROR; return code from pthread_join() is "<< rc <<endl;
exit(-1);
}
cout<<"Main: completed join with RESOLVER thread " << t <<" having a status of "<<(long)status<<endl;
}
delete[] tasks;
delete[] TaskQueueRequests;
delete[] TaskQueueResolves;
//delete[] requestersThreads;
//delete[] reoslveThreads;
pthread_mutex_destroy(&TaskQueueResolves_lock);
pthread_cond_destroy(&TaskQueueResolves_cond);
线程池.h
void initRequestThreads(pthread_t **threads)
{
// add the attribute join for the threads
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc;
cout << "DEBUG "<< __LINE__<<": numOfThreads:"<<numOfThreadsRequests<<endl;
for(long i = 0; i < numOfThreadsRequests; i++)
{
threads[i] = new pthread_t;
rc = pthread_create(&(*threads[i]), &attr, ThreadPool::OperationRequestThread, (void *)this); // create thread that get all the thread pool object(this) and preform OperationRequest function
if(rc)
{
cout <<"creating Request thread failed! Error code returned is:"+rc<<endl;
exit(-1);
}
cout << "DEBUG "<< __LINE__<<": Creating Request Thread #" << i+1 << "!\n";
}
pthread_attr_destroy(&attr);
}
【问题讨论】:
-
您是否根据错误编号(
EINVAL, ....)测试了pthread_join的返回值,它对您的帮助不仅仅是原始错误值。您的代码是 C 和 C++ 的混乱。尝试清理它(使用vector而不是T*,...)
标签: c++ multithreading pthreads pthread-join