下面的程序在随机实例上给出了段错误(核心转储)错误。有时它运行没有任何错误。该程序只是为了理解死锁。
尽管我已经运行这个程序大约 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/