简体   繁体   English

pthread 和 mutex_lock 抛出分段核心转储

[英]pthread and mutex_lock throwing segmentation core dumped

I am trying to play with threads using a mutex for syncronization, but it seems that my code throws a " segmentation fault core dumped " error every time after compiling it.我正在尝试使用互斥锁来使用线程进行同步,但似乎我的代码在每次编译后都会引发“分段错误核心转储”错误。

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

}

Two things:两件事情:

  1. You are dereferencing a NULL pointer here:您在此处取消引用 NULL 指针:

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

    Since you define int *s = 0;由于您定义int *s = 0; globally.全球范围内。 You probably wanted to define it as int s = 0;您可能想将其定义为int s = 0; and then use s everywhere instead of *s .然后在任何地方使用s而不是*s

  2. As noted by Rainer Keller in the comments, you are not initializing your mutex . 正如Rainer Keller在评论中指出的那样,您没有初始化mutex You should either initialize it statically to PTHREAD_MUTEX_INITIALIZER , or at runtime in main with pthread_mutex_init(&mutex) .您应该将其静态初始化为PTHREAD_MUTEX_INITIALIZER ,或者在运行时在main中使用pthread_mutex_init(&mutex)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM