[英]How to return value from the thread back to main function without using blocking function in C++/C
[英]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;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.