我的线程创建有问题使用P线程。我想有人能解决问题所在。我的代码如下,由于空间限制,我只显示了一部分。
Main.c create Detectdirection instance and send to the function.
d = new Detectdirection();
while(run)
{
int ret = d->run_parallel(d);
if(ret == -1)
run = false;
}我的Detectdirection有两个函数可以并行运行。
class Detectdirection{
public:
int run_parallel(void*p);
void *Tracking(void *p);
static void *Tracking_helper(void * p);
void *ReadImage(void *p );
static void *ReadImage_helper(void *p );
private:
pthread_t thread[2];
}
void *Detectdirection::ReadImage(void *p){
Detectdirection *app = (Detectdirection*)p;
while(run){
}
pthread_exit(NULL);
}
void *Detectdirection::Tracking(void *p){
Detectdirection *app = (Detectdirection*)p;
while(run){
}
pthread_exit(NULL);
}
void *Detectdirection::Tracking_helper(void *p){
Detectdirection *app = (Detectdirection*)p;
return ((Detectdirection*)p)->Tracking(app);
}
void *Detectdirection::ReadImage_helper(void *p ){
Detectdirection *app = (Detectdirection*)p;
return ((Detectdirection*)p)->ReadImage(app);
}
int Detectdirection::run_parallel(void* p){
Detectdirection *app = (Detectdirection*)p;
int rc = pthread_create(&thread[0], NULL, app->ReadImage_helper, app);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
return -1;
}
rc = pthread_create(&thread[1], NULL, app->Tracking_helper, app);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
return -1;
}
return 0;
}编译是可以的,当我运行时,我有线程创建错误。这种类型的返回类型11只在创建了许多线程时才会发生。但是现在我只创建了两个线程,并且我有了这个错误。有什么不对的?
发布于 2017-01-04 14:05:06
我相信您正在获得EAGAIN (基于错误代码11)。这意味着您的系统没有足够的资源来创建线程。
POSIX文件说:
EAGAIN系统缺乏创建另一个线程所需的资源,否则将超出系统对进程{PTHREAD_THREADS_MAX}中线程总数的限制。
我不太确定以下内容是否属实。
但是现在我只创建了两个线程,并且我有了这个错误。有什么不对的?
这里,
while(run)
{
int ret = d->run_parallel(d);
if(ret == -1)
run = false;
}您是在循环中创建的,每个调用d->run_parallel()都会创建两个线程。因此,您可能会创建无限多的线程,因为只有当pthread_create()失败时,循环才会中断。因此,您可能希望仔细查看这个循环是否真的想要像现在这样做。
您似乎没有加入您创建的线程。因此,您可以分离线程,以便在线程退出时立即释放特定于线程的资源。你可以:
pthread_detach(pthread_self());在ReadImage_helper()和Tracking_helper()函数中分离它们。这可能会解决您的资源问题。
如果它仍然存在,那么您必须研究限制系统上同时运行的线程数量的方法。一种可能的选择是使用thread pools --创建固定数量的线程,并在线程完成当前任务时为它们分配新任务。
https://stackoverflow.com/questions/41459177
复制相似问题