【发布时间】:2015-02-06 21:26:33
【问题描述】:
我正在玩一个相当简单的 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
我错过了什么吗?
【问题讨论】: