我開始學習在 Linux 上使用 C 進行多執行緒編程。下面是我的練習和我為每個執行緒執行 hello 函式的代碼。請告訴我有什么問題。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#define NUM_THREADS 4
void *hello(void * );
int main() {
int j;
pthread_t tid[NUM_THREADS];
printf("My process ID %d\n", getpid());
for (j = 0; j < NUM_THREADS; j )
pthread_create(&tid[j], NULL, hello, (void*)j); //original is pthread_create([1])
for (int i = 0; i < NUM_THREADS; i )
pthread_join(tid[i], NULL); //original is pthread_join([2])
return 0;
}
void *hello(void * my_id) {
printf("Hello World from branch thread %d\n", *(int * ) my_id);
}
下面只有兩行可能出錯,因為這是一個填空練習,下面兩行是我添加的。我想這是(void*)j
pthread_create(&tid[j], NULL, hello, (void*)j); //[1]
pthread_join(tid[i], NULL); //[2]
[1] 用 tid 創建子執行緒,每個子執行緒執行帶引數 j 的 hello 函式。
[2] 是主執行緒只有在所有子執行緒結束時才結束
我沒有預期的輸出。但是我對高級請求有一個預期的輸出(需要更改原始代碼的某些部分,不僅要填寫[1]和[2]),如下所示:
My process ID 127
Hello World from branch thread 0
Hello World from branch thread 1
Hello World from branch thread 2
Hello World from branch thread 3
我的錯誤是:
quang@quang-VirtualBox:~$ gcc exe2_1.c -o exe2_1 -pthread
exe2_1.c: In function ‘main’:
exe2_1.c:32:42: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
32 | pthread_create(&tid[j], NULL, hello, (void*)j)
Please understand that my first subject was Python, this is my second subject (operating system), I have zero knowledge of C, but my school force me to learn this. I just need the fixed code so that I can submit.
uj5u.com熱心網友回復:
您沒有指定預期的輸出。解決方案取決于您是否希望從每個執行緒中看到不同的數字,或者是否某些執行緒可能會列印相同的數字。
要修復來自編譯器的訊息,您必須提供一個真正的指標。不僅僅是您轉換為指標的一些整數。
如果你這樣做
int j = 1;
pthread_create(&tid[j], NULL, hello, (void*)j);
這將導致hello被呼叫,1其中包含一個整數值。但是hello認為,它是一個指標并試圖取消參考它。這行不通。
相反,您必須提供某個int變數的地址。將相關行更改為
pthread_create(&tid[j], NULL, hello, &j);
會成功的。
但是......(正如你同時評論的那樣)
您注意到,如果您這樣做,所有執行緒都會列印相同的數字。發生這種情況是因為您將相同變數的相同地址傳遞給每個執行緒。并且執行緒執行時沒有特定的順序。很有可能在整個回圈完成后執行第一個執行緒。為避免這種情況,您必須為每個執行緒提供不同的值。您不能僅通過向該函式呼叫添加引數來做到這一點。相反,您必須為每個執行緒提供單獨的記憶體。你可以這樣做:
int params[NUM_THREADS];
for (j = 0; j < NUM_THREADS; j )
{
params[j] = j;
pthread_create(&tid[j], NULL, hello, ¶ms[j]);
}
這將導致每個執行緒列印不同的數字。
uj5u.com熱心網友回復:
非常簡單,您將引數 j 的傳遞過于復雜,您只需要使用 & 傳遞其地址
語法是
int pthread_create(pthread_t *thread, pthread_attr_t *attr,
void *(*start_routine) (void *arg), void *arg);
傳遞給函式
void *thread(void *arg)
你的行應該是
pthread_create(&tid[j], NULL, hello, &j);
鍛煉的預期輸出
Hello World from branch thread 1
Hello World from branch thread 2
Hello World from branch thread 3
Hello World from branch thread 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450001.html
標籤:c linux multithreading pthreads
上一篇:如何遍歷目錄及其所有子目錄?
