gpt4 book ai didi

c++ - pthread_join 错误代码 3

转载 作者:行者123 更新时间:2023-11-28 01:48:06 26 4
gpt4 key购买 nike

我的项目有问题。它抛出错误代码 3。

我只是添加了部分代码,让您看看我做了什么。在 main.cpp 中,我在线程上声明,然后发送到 initRequestThreads(in thread.h) 来创建线程。然后在 main.cpp 中让主进程等待它。

主要.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);

最佳答案

您收到的错误代码是 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 .如果您出于某种原因绑定(bind)到 C++2003,您至少应该停止这种糟糕的动态数组业务并将指针传递给它们,而是使用 std::vector<pthread_t>作为函数的输出参数。

关于c++ - pthread_join 错误代码 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com