我正在嘗試使用互斥鎖來處理執行緒進行同步,但似乎我的代碼在每次編譯后都會拋出“分段錯誤核心轉儲”錯誤。
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex;
int *s = 0;
void *fonction(void * arg0) {
pthread_mutex_lock( & mutex);
*s = *((int *)arg0) * 1000000;
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_t thread[5];
int ordre[5];
for (int i = 0; i < 5; i )
ordre[i] = i;
for (int i = 0; i < 5; i )
pthread_create(&thread[i], NULL, fonction, & ordre[i]);
for (int i = 0; i < 5; i )
pthread_join(thread[i], NULL);
printf("%d\n", * s);
return 0;
}
uj5u.com熱心網友回復:
兩件事情:
您在此處取消參考 NULL 指標:
*s = *((int *)arg0) * 1000000;既然你定義了
int *s = 0;全域。您可能想將其定義為int s = 0;,然后s在任何地方使用,而不是*s.正如 Rainer Keller在評論中指出的那樣,您沒有初始化您的
mutex. 您應該將其靜態初始化為PTHREAD_MUTEX_INITIALIZER,或者在運行時將其初始化main為pthread_mutex_init(&mutex)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380472.html
