簡體   English   中英

pthreads - 強制線程運行

[英]pthreads - force thread to run

我有一個從主線程調用的 function:

void create_thread() {    
    pthread_t bg_thread;
    pthread_create(&bg_thread, NULL, run_in_background, NULL);

    //wait here
    pthread_mutex_lock(&MAIN_MUTEX);
    pthread_cond_wait(&wakeUpMainThread, &MAIN_MUTEX);
    pthread_mutex_unlock(&MAIN_MUTEX);

    pthread_cond_signal(wakeUpBgThread);
}

這是在后台線程中運行的 function 的簡短版本:

void* run_in_background(void* v) {                   
    pthread_mutex_t mutex;
    pthread_cond_t  cond;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    //NOTE: wakeUpBgThread == cond
    save_condition_and_mutex(&cond, &mutex);

    pthread_mutex_lock(&mutex);
    {
        pthread_cond_signal(&wakeUpMainThread);

        while( run_condition ) {
            pthread_cond_wait(&cond, &mutex);

            do_smth();
        }
    }
    pthread_mutex_unlock(&mutex);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    pthread_exit(NULL);
}

所以目標是:

1. Create a thread in the main one.
2. Make the main thread sleep until the signal from that thread.
3. Make the background thread sleep until the signal from the main thread.
4. Invoke the background thread from the main one.

問題是:有時在

 pthread_cond_signal(&wakeUpMainThread);

調度程序立即切換到主線程並為后台線程觸發喚醒信號。 在此調度程序切換回后台線程並開始等待已經觸發的信號后,它會永遠休眠。

問題:有沒有辦法強制后台線程執行代碼,直到

pthread_cond_wait(&cond, &mutex);

您在create_thread中對pthread_mutex_lock的調用需要在pthread_create之前進行,而不是之后。 否則你有一個競爭條件。

使用信號量? 信號量信號不會丟失——它們只是增加計數,因此后台線程在信號量發出信號后再次運行,即使它實際上還沒有開始等待它。

Rgds,馬丁

聽起來你最好的選擇是使用條件。 有一個互斥鎖和一個條件。 Main 初始化兩者,獲取互斥體,創建線程,然后根據條件進入睡眠狀態。 child 搶鎖(在 main 等待條件之后)做工作(或者做工作然后搶鎖),然后發出條件信號(你可以決定是在信號之前還是之后釋放鎖——重要的一點是你抓住了它)。 Main 然后喚醒並繼續處理。

pthread_cond_wait() 和朋友就是你所看到的。

您不會在主線程上的信號之前鎖定互斥鎖。 如果您想要可預測的行為 - 您應該在等待調用和信號調用之前鎖定相同的互斥鎖。

暫無
暫無

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

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