我正在處理一個大型專案,我正在嘗試創建一個執行以下操作的測驗:首先,創建 5 個執行緒。每個執行緒將創建 4 個執行緒,而每個執行緒又創建 3 個其他執行緒。所有這一切都發生到 0 個執行緒。我有_ThreadInit()函式用于創建執行緒:
status = _ThreadInit(mainThreadName, ThreadPriorityDefault, &pThread, FALSE);
其中第三個引數是輸出(創建的執行緒)。
我想要做的是從必須創建n = 5的多個執行緒開始,如下所示:
for(int i = 0; i < n; i ){
// here call the _ThreadInit method which creates a thread
}
我被困在這里。請有人幫我理解應該如何做。謝謝^^
uj5u.com熱心網友回復:
基于 Eugene Sh. 的評論,您可以創建一個函式,該函式接受一個引數,即要創建的執行緒數,該函式以遞回方式呼叫自身。
使用標準 C 執行緒的示例:
#include <stdbool.h>
#include <stdio.h>
#include <threads.h>
int MyCoolThread(void *arg) {
int num = *((int*)arg); // cast void* to int* and dereference
printf("got %d\n", num);
if(num > 0) { // should we start any threads at all?
thrd_t pool[num];
int next_num = num - 1; // how many threads the started threads should start
for(int t = 0; t < num; t) { // loop and create threads
// Below, MyCoolThread creates a thread that executes MyCoolThread:
if(thrd_create(&pool[t], MyCoolThread, &next_num) != thrd_success) {
// We failed to create a thread, set `num` to the number of
// threads we actually created and break out.
num = t;
break;
}
}
int result;
for(int t = 0; t < num; t) { // join all the started threads
thrd_join(pool[t], &result);
}
}
return 0;
}
int main() {
int num = 5;
MyCoolThread(&num); // fire it up
}
運行統計:
1 thread got 5
5 threads got 4
20 threads got 3
60 threads got 2
120 threads got 1
120 threads got 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349071.html
上一篇:共享檔案夾中兩個執行緒之間的同步
