pthread 和 mutex_lock 抛出分段核心转储

pthread and mutex_lock throwing segmentation core dumped

我正在尝试使用 互斥体 来实现 线程 同步,但似乎我的代码抛出一个“segmentation fault core dumped" 每次编译后都会出错。

#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;

}

两件事:

  1. 您在此处取消引用 NULL 指针:

    *s += *((int *)arg0) * 1000000;
    

    由于您在全局范围内定义了 int *s = 0;。您可能想将其定义为 int s = 0;,然后到处使用 s 而不是 *s.

  2. Rainer Keller 在评论中,你没有初始化你的 mutex。您应该将其静态初始化为 PTHREAD_MUTEX_INITIALIZER,或者在运行时使用 pthread_mutex_init(&mutex).

    main 中初始化