我正在使用一个相当简单的C语言示例。该程序创建两个线程并并行启动它们。每个线程都被设计为使用Mutex修改一个全局变量,并将值打印出来。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int A=10;
pthread_mutex_t M;
void *codice_Th1(void *arg) {
int i;
for (i=0; i<10;i++){
pthread_mutex_lock(&M);
printf("Thread %s: ", (char *)arg);
A++;
printf("A = %d \n", A);
pthread_mutex_unlock(&M);
sleep(1);
}
pthread_exit(0);
}
void *codice_Th2(void *arg) {
int i;
for (i=0; i<10;i++){
pthread_mutex_lock(&M);
printf("Thread %s: ", (char *)arg);
A--;
printf("A = %d \n", A);
pthread_mutex_unlock(&M);
sleep(1);
}
pthread_exit(0);
}main()只是创建线程,并将主线程与线程1和2连接起来。
int main(){
pthread_t th1, th2;
...
}让我感到困扰的是,我得到了以下输出
Thread th1: Thread th2: A = 11
A = 10
Thread th1: A = 11
Thread th2: A = 10
Thread th1: Thread th2: A = 11
A = 10
Thread th1: Thread th2: A = 11
A = 10
Thread th2: Thread th1: A = 9
A = 10
Thread th1: A = 11
Thread th2: A = 10而我希望每一行都按顺序执行printf语句,因为它们都在互斥锁中。
换句话说,我不能理解输出
Thread th2: Thread th1: A = 9我希望总是有类似的东西
Thread NAME: A = VALUE我是不是遗漏了什么?
发布于 2015-02-07 05:33:54
没关系,我相信我找到了问题所在。在使用互斥锁之前,我没有用pthread_mutex_init(&M, NULL);初始化它。
设置
int main(){
pthread_t th1, th2;
int ret;
pthread_mutex_init(&M, NULL);已修复此问题。我假设使用pthread_mutex_init是必需的。不幸的是,跳过互斥锁初始化不会产生任何警告或错误。脚本以静默方式编译。
https://stackoverflow.com/questions/28375084
复制相似问题