【发布时间】:2017-09-15 22:44:34
【问题描述】:
我有一些东西要计算,它们在某种程度上相互依赖(其中一些计算可能表明不需要列表中的其他计算)。
我还想一次计算其中两个(两个子线程和一个主线程(这是另一个的子线程,但这是另一回事)。
所以我希望主线程等待两个线程中的任何一个-首先完成的线程使主线程继续-。在它继续之后,它会运行一些代码来查看另一个正在运行的线程是否可以被杀死(如果完成的那个表明另一个不需要),并且还运行一个新线程。
这个想法是做这样的事情:
while (/*list not empty*/) {
/*detect which two entries need to be calculated*/
/*detect if running thread can be killed*/
if (/*running thread can be killed*/) {
pthread_join(/*threadnum*/, NULL)
}
switch (/*how many threads already running?*/) {
case 0:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
case 1:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
break;
}
/* !!!!!!!!! Question code is next line: !!!!!!!!!*/
pthread_join(/*What goes here?*/, NULL);
// If it is impossible to do with pthread_join, what else can be used?
}
我的第一种方法(如果这是不可能的)是将两个线程的状态存储在一个数组中,并检查每一秒(一段时间和睡眠(1))是否有任何一个完成,但这会让我每次线程完成都会浪费时间(0 到 1 秒之间)。所以我想尽可能避免这种情况。
编辑: pthread_cond_wait(/* something */) 似乎是要走的路。但是我希望它变得简单:主线程和两个子线程共享一个全局变量(父),如果子线程正在运行,则设置为 0,当其中一个停止时设置为 1。理想情况下,我想以这种方式从主线程控制一切:
while (/*list not empty*/) {
/*detect which two entries need to be calculated*/
/*detect if running thread can be killed*/
if (/*running thread can be killed*/) {
pthread_join(/*threadnum*/, NULL)
}
switch (/*how many threads already running?*/) {
case 0:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
case 1:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
break;
}
/* !!!!!!!!! Question code is next line: !!!!!!!!!*/
pthread_cond_wait(parent, /*wtf?*/)
}
现在我有一个想法,在满足该条件之前停止父级,我可以在子线程中将其设置为 1。
【问题讨论】:
-
你了解如何使用条件变量吗?如果没有,我会从学习如何相当彻底地使用它们开始。另外,这里有一个非常有价值的提示——停止考虑等待线程或停止线程。线程只是碰巧在做这项工作的事物,但它是您想要等待或停止的工作。你想等到一些工作完成。你想阻止一些工作完成。不要考虑工作会发生什么,要考虑工作本身。
-
@DavidSchwartz 是的,我知道条件变量。问题是:我知道在 C 中等待某事的唯一方法有两种: 1.- pthread_join():据我所知,你只能用它来等待一个线程,而不是两个,所以它没有用。 2.- 每 x 次检查一次工作是否完成(while 和 Sleep()),这会让你失去线程完成和在主线程意识到这一点之间的时间。
-
所有 cmets,但我特别询问那里有什么,不是因为我不知道放什么,而是通用。
-
“我知道条件变量。问题是:我知道在 C 中等待某事的唯一方法是两种……” - 条件变量是第三种方法……
-
好吧,我以为他在谈论 ifs 的变量。我不知道存在专门用于 pthreading 的称为“条件变量”的东西,所以很抱歉。
标签: c pthreads pthread-join