我的项目有问题。 它引发了我错误代码3。
我只是添加部分代码,让你看看我做了什么。 在main.cpp中我在线程上声明然后我发送到initRequestThreads(在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);
ThreadPool.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);
}
答案 0 :(得分:2)
您获得的错误代码是ESRCH
- 这意味着您尝试加入的主题不存在。
原因就是代码中关于如何处理线程ID的未定义行为的可怕混乱。
pthread_t *requestersThreads = new pthread_t[Length_Tasks];
这将创建一个包含N个线程的数组,而不是将指向此数组的指针传递给
中的函数initRequestThreads(&requestersThreads);
现在,在你的线程创建循环中,你做
threads[i] = new pthread_t;
pthread_create(&(*threads[i]), &attr /*... */
在这里,你完全搞乱你的数组并触发未定义的行为。在您的函数中,threads
不是数组!它是数组的地址。您无法使用array subscript operator
([]
)访问它。其余的只是对已经发生的伤害进行侮辱。
如果您正在编写C ++ 11及更高版本(正如您在2017年所做的那样),那么您应该使用C ++ 11 std::thread
。如果由于某种原因绑定到C ++ 2003,那么至少应该停止动态数组这个可怕的业务并将指针传递给那些,而是使用std::vector<pthread_t>
作为函数的输出参数。