·等待C中的各种线程中的第一个

时间:2017-09-15 22:44:34

标签: c pthreads pthread-join

我有一些类似于要计算的事物列表,它们在某种程度上依赖于彼此(其中一些计算,可能表明不需要列表上的其他计算)。

此外,我想一次计算其中两个(两个子线程和一个主线程(这是另一个的子线程,但这是另一个故事))。

所以我希望主线程等待两个步骤中的任何一个 - 首先完成的一个使主线程继续 - 。继续之后,它将运行一些代码以查看是否可以杀死另一个正在运行的线程(如果完成的线程显示另一个不需要),还是运行新线程。

这个想法是做这样的事情:

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(/ *某事* /)似乎要走了。但是我希望它很容易:主线程和两个子线程共享一个全局变量(父),如果子线程正在运行,则设置为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。

1 个答案:

答案 0 :(得分:0)

不要使主线程监视器并尝试杀死其他线程,而是让其他线程直接在它们之间进行通信。

例如,如果线程A完成并且很明显不再需要线程B中的计算,则只需设置一个布尔标志。让线程B在其计算步骤之间检查该标志,并在设置标志时放弃。

尝试中断线程是不好的做法 - 最好只设置线程将检查的标志。

相关问题