这是一个简单的代码,它在每个线程中添加两个数字,然后最终给出总余额:
#include <pthread.h>
#include <stdio.h>
int currentBalance=100,newBalance=0,oldBalance=0;
pthread_mutex_t mutex;
void* thread1(){
pthread_mutex_lock(&mutex);
oldBalance = currentBalance;
newBalance = oldBalance + 10000;
currentBalance = newBalance;
pthread_mutex_unlock(&mutex);
}
void* thread2(){
pthread_mutex_lock(&mutex);
oldBalance = currentBalance;
newBalance = oldBalance + 5000;
currentBalance = newBalance;
pthread_mutex_unlock(&mutex);
}
void* thread3(){
pthread_mutex_lock(&mutex);
currentBalance = currentBalance;
newBalance = oldBalance + 5500;
currentBalance = currentBalance;
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t trd1,trd2,trd3;
pthread_attr_t attr;
pthread_mutex_init(&mutex,NULL);
pthread_attr_init(&attr);
pthread_create(&trd1,NULL,thread1,NULL);
pthread_join(trd1,NULL);
pthread_create(&trd2,NULL,thread2,NULL);
pthread_join(trd2,NULL);
pthread_create(&trd3,NULL,thread3,NULL);
pthread_join(trd3,NULL);
printf("Current Balance: %d\n",currentBalance);
return 0;
}
我正在尝试使用命令进行编译
gcc -pthread task6.c
我不知道哪里出了问题,代码很好。请指导我一下。谢谢!