【问题标题】:Synchronizing screen output with mutex and pthread使用 mutex 和 pthread 同步屏幕输出
【发布时间】: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

我错过了什么吗?

【问题讨论】:

    标签: c pthreads mutex


    【解决方案1】:

    没关系,我相信我找到了问题所在。在使用之前,我没有使用 pthread_mutex_init(&amp;M, NULL); 初始化 Mutex。

    设置

    int main(){
      pthread_t th1, th2;
      int ret;
    
      pthread_mutex_init(&M, NULL);
    

    解决了这个问题。我假设使用pthread_mutex_init 是一项要求。不幸的是,跳过互斥体初始化不会产生任何警告或错误。脚本静默编译。

    【讨论】:

    • 将来包括您的main 函数的全部(或至少相关部分),这样我们也可以找到这些错误:)
    • @Daniel 你是绝对正确的。我错误地认为main() 足够简单,不值得发布。
    • 它不会在编译时产生警告或错误... 你的编译器怎么知道这个函数应该被调用?如果它真的被调用,它将如何找到?请记住,不初始化变量是 C 语言中一个非常常见的错误,这不是被禁止的。使用它们是UB。这正是您使用互斥锁时发生的事情。
    • @Jean-BaptisteYunès 编译器无法理解它们是否曾经被使用过,但它仍然可以静态检测是否存在涉及互斥锁的方法调用,并警告您可能的“未初始化互斥体调用”。但我不知道C 足以证明我的假设是有道理的。 :)
    • 不,他不能。您正在考虑过于简单的情况。考虑在一个函数中初始化,在另一个函数中使用它......如果对这些函数的调用有点复杂,您的编译器将无法确定它们是否被正确调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    相关资源
    最近更新 更多