c - 随机运行实例的段错误

标签 c segmentation-fault deadlock coredump

下面的程序在随机实例上给出了段错误(核心转储)错误。有时它运行没有任何错误。该程序只是为了理解死锁。

尽管我已经运行这个程序大约 15 次,但到目前为止我还没有遇到过死锁。有时程序运行顺利(这是可以预期的),有时会出现段错误(这是不可预期的)。为什么我会出现段错误?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

int a=5;
int b=3;

pthread_mutex_t mutex1,mutex2;


void* add_subtract(){

    pthread_mutex_lock(&mutex1);
    pthread_mutex_lock(&mutex2);
    a=a+2;
    b=b-2;
    printf("%d %d\n",a,b);
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);



}


void* subtract_add(){


    pthread_mutex_lock(&mutex2);
    pthread_mutex_lock(&mutex1);
    b=b-2;
    a=a+2;
    printf("%d %d\n",a,b);

    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);

}
int main(){

    pthread_t thread1,thread2;
    pthread_create(&thread1,NULL,add_subtract(),NULL);
    pthread_create(&thread2,NULL,subtract_add(),NULL);
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

最佳答案

当您将 add_subtract() 作为参数传递时,您将调用该函数,然后将返回值作为参数传递。在这种情况下,您想传递函数本身...尝试不带括号。

关于c - 随机运行实例的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727606/

相关文章:

c - 我如何让 yacc/bison 和/或 lex/flex 在 token 替换后重新开始扫描?

c++ - 尽管使用等效语句但出现段错误的原因

C++ unordered_map SIGSEGV on find() 或 insert()

c - pthread_mutex_trylock 段错误

java - EJB 两个单例相互调用死锁

MySQL 子查询死锁(某种)

c - 多个字符串的空间分配

c - 32 位机器如何处理大于 2^32 的数字?

clock() 函数无法按预期使用排序函数

c - 分段故障