簡體   English   中英

·等待C中的各種線程中的第一個

[英]·Wait for first of various threads in C

我有一些要計算的東西列表,它們在某種程度上相互依賴(其中一些計算可能表明不需要列表上的其他計算)。

我也想一次計算總是兩個(兩個子線程和一個主線程(這是另一個線程的子線程,但這又是另一回事了))。

因此,我希望主線程等待兩個踏步中的任何一個-首先完成的踏步使主線程繼續前進。 繼續之后,它將運行一些代碼以查看是否可以終止另一個正在運行的線程(如果完成的線程表明不需​​要另一個線程),也可以運行一個新線程。

這個想法是做這樣的事情:

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?
}

我的第一種方法(如果不可能的話)是將兩個線程的狀態存儲在數組中,並每秒檢查一次(帶有一會兒和sleep(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。

不必讓主線程監視並嘗試殺死其他線程,而應讓其他線程直接在它們之間進行通信。

例如,如果線程A完成並且很明顯不再需要線程B中的計算,則只需設置一個布爾標志。 使線程B在其計算步驟之間檢查該標志,並放棄該標志是否已設置。

嘗試中斷線程是一種不好的做法-最好只設置一個線程將檢查的標志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM