等待多个信号 - pthread
我正在构建一个简单的作业系统,它允许我创建一个具有依赖关系的作业图...类似于:
Job root;
Job job1;
Job job1_1;
Job job1_2;
Job job2(&job1, 1); // job2 cannot start until job1 finishes.
job1.addJob(&job1_1);
job1.addJob(&job1_2);
root.addJob(&job1);
root.addJob(&job2);
root.execute(); // execute the job graph.
我正在使用 pthreads 来实现这个,但我是这种类型的程序的新手,我找不到同步所有这些的方法。
我尝试使用 pthread_join 来做这样的事情:
void Job::execute()
{
for(int i = 0; i < numDependencies; ++i)
dependencies[i].join(); // calling pthread_join
for(int i = 0; i < numSubJobs; ++i)
subJobs[i].start(); // calling pthread_create
... do some work here
for(int i = 0; i < numSubJobs; ++i)
subJobs[i].join(); // calling pthread_join
}
但是我的程序在其中一个 pthread_join 调用中崩溃了。
来自 pthread 文档:
多次同时调用 pthread_join() 的结果 指定相同的目标线程是未定义的。
我怎样才能获得相同的结果但又不会崩溃?
谢谢
I am building a simple job system that would allow me to create a job graph with dependencies... Something like:
Job root;
Job job1;
Job job1_1;
Job job1_2;
Job job2(&job1, 1); // job2 cannot start until job1 finishes.
job1.addJob(&job1_1);
job1.addJob(&job1_2);
root.addJob(&job1);
root.addJob(&job2);
root.execute(); // execute the job graph.
I am using pthreads to implement this but I am new to this type of programs and I cant find a way to synchronize all this.
I tried using pthread_join to do something like this :
void Job::execute()
{
for(int i = 0; i < numDependencies; ++i)
dependencies[i].join(); // calling pthread_join
for(int i = 0; i < numSubJobs; ++i)
subJobs[i].start(); // calling pthread_create
... do some work here
for(int i = 0; i < numSubJobs; ++i)
subJobs[i].join(); // calling pthread_join
}
But my program crash in one of the pthread_join call.
From the pthread documentation :
The results of multiple simultaneous calls to pthread_join()
specifying the same target thread are undefined.
How can I achieve the same results but without the crash?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pthred_join() 等待创建的线程终止。程序崩溃是因为您使用的是 Job 的未初始化成员(假设 pthread_t thread; )。如果作业线程是在 start() 方法中创建的,那么您应该将execute() 重写为:
在这种情况下,您将不会得到*多个同时调用 pthread_join() 指定相同的目标线程*(而且这不是问题)你的情况也是如此)。
pthred_join() waits for created thread termination. And program crashes because you are using uninitialized members of Job (let's say pthread_t thread; ). If job thread is created in start() method, then you should rewrite execute() as:
You will not get *multiple simultaneous calls to pthread_join() specifying the same target thread* in this case (and moreover this was not an issue in your case also).