使用互斥锁和pthread同步屏幕输出

时间:2015-02-06 21:26:33

标签: c pthreads mutex

我正在玩一个相当简单的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

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

没关系,我相信我发现了这个问题。在使用之前,我没有使用pthread_mutex_init(&M, NULL);初始化互斥锁。

设置

int main(){
  pthread_t th1, th2;
  int ret;

  pthread_mutex_init(&M, NULL);

解决了这个问题。我认为使用pthread_mutex_init是必需的。不幸的是,跳过互斥锁初始化没有产生任何警告或错误。该脚本默默编译。

相关问题