我有一个要计算的事物列表,它们在某种程度上相互依赖(其中一些计算可能表明不需要列表中的其他计算)。
此外,我想一次总是计算其中两个(两个子线程和一个主线程(这是另一个线程的子线程,但那是另一回事了))。
所以我希望主线程等待两个线程中的任何一个 - 首先完成的线程使主线程继续 -。继续之后,它将运行一些代码来查看是否可以杀死另一个正在运行的线程(如果完成的线程表明不需要另一个线程),并且还运行一个新线程。
这个想法是做这样的事情:
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?
}
我的第一个方法(如果这是不可能的)是将两个线程的状态存储在一个数组中,并每秒检查一次(用 while 和 sleep(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。
最佳答案
不要让主线程监视器并尝试杀死其他线程,而是让其他线程直接在它们之间进行通信。
例如,如果线程 A 完成并且很明显不再需要线程 B 中的计算,只需设置一个 bool 标志即可。让线程 B 在其计算步骤之间检查该标志,如果设置了该标志则放弃。
尝试中断线程是不好的做法 - 您最好只设置一个线程将检查的标志。
关于c - ·等待C中各个线程中的第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248340/