簡體   English   中英

C++ pthread - 如何在不等待完成的情況下從線程 function 返回值?

[英]C++ pthread - how to return a value from thread function without waiting for finish?

我按照基本的 c++ 教程制作多線程。 我有繪制循環,在框架中我啟動了幾個線程。 我不等待 pthread_join 的線程結果,而是繼續繪制其他對象。 如果適當對象的並條機檢測到所有線程都已完成,那么我將啟動“threadsFinished”function。 在我寫的時候,我不使用 pthread_join,相反,我喜歡將結果寫入啟動這些線程的 object,在我的例子中是 class 程序。 我通過線程 function 中的指針訪問了“程序”object,我可以在此處將結果寫入此 object,但它是線程安全的嗎? 或者我應該將互斥鎖與程序 object 一起使用?

這是我的代碼:

void Program::onDraw(Matrix *matrix) {
    fireThreads();
    ....

    if (threadsStarted && threadsFinishedCount == NUM_THREADS) {
        threadsFinished();
    }
    ...draw other stuff, progress bar etc... 
}

void *Program::threadFunction(void *threadData) {
    thread_data *data = static_cast<thread_data*>(threadData);
    Program *program = static_cast<Program*>(data->owner);
    program->threadsFinishedCount++;

    pthread_exit(NULL);
}

void Program::fireThreads() {
    if (threads == NULL) {
        threads = new pthread_t[NUM_THREADS];
        threadData = new thread_data[NUM_THREADS];
    }

    int rc;
    int i;

    threadsFinishedCount = 0;
    threadsStarted = true;

    for( i = 0; i < NUM_THREADS; i++ ) {
        threadData[i].threadId = i;
        threadData[i].owner = this;

        rc = pthread_create(&threads[i], NULL, updateDB, (void *)&threadData[i]);

        if (rc) {
            ...
        }
    }
}

使用的變量是這樣定義的:

class Program {
...
    static void *threadFunction(void *threadId);
    bool threadsStarted;
    volatile int threadsFinishedCount;
...
}

我可以在這里將結果寫入這個 object,但它是線程安全的嗎?

不,它不是線程安全的。 在 C/C++ 中,如果多個線程同時訪問同一個 object 並且其中至少一個訪問是修改,那么您就有數據競爭,這會導致未定義的行為 線程同步原語,如 mutex 和atomic ,是此規則的例外,因此您必須使用其中之一來實現線程安全。

請注意, volatile也不例外,而且從來都不是; volatile對象的並發訪問仍然會導致競爭條件。

暫無
暫無

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

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