c - 一些我无法理解的简单 C 代码 - 互斥锁在这里做什么?

标签 c mutex

抱歉刚刚在这里找到这段代码 - http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html并且用这段代码解释了互斥锁,但它让我有点不知所措。我了解互斥锁的功能,并且它在关键部分保护共享变量。虽然这里的细节让我感到困惑!据我了解,我们正在使用 pthread_create 创建一个新线程,它正在运行 functionC 进程,该进程递增一个计数器。计数器是 protected 变量,并且由于两个函数同时运行,如果计数器不受互斥量保护,它会返回错误的值。

这是正确的/接近的吗?非常感谢:)。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0;

main()
{
   int rc1, rc2;
   pthread_t thread1, thread2;

   /* Create independent threads each of which will execute functionC */

   if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc1);
   }

   if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc2);
   }

   /* Wait till threads are complete before main continues. Unless we  */
   /* wait we run the risk of executing an exit which will terminate   */
   /* the process and all threads before the threads have completed.   */

   pthread_join( thread1, NULL);
   pthread_join( thread2, NULL); 

   exit(0);
}

void *functionC()
{
   pthread_mutex_lock( &mutex1 );
   counter++;
   printf("Counter value: %d\n",counter);
   pthread_mutex_unlock( &mutex1 );
}

最佳答案

如果您没有适当的互斥锁,可能会发生这种情况:

// initialization
counter = 0;

// thread 1 runs:
counter++;

// context switch
// thread 2 runs:
counter++;

// context switch
// thread 1 runs and printf "Counter value: 2"
printf("Counter value: %d\n",counter);

// context switch
// thread 2 runs and printf "Counter value: 2"
printf("Counter value: %d\n",counter);

因此,您最终可能会得到以下输出:

Counter value: 2
Counter value: 2

现在,有了互斥量,您可以确保增量及其打印将自动运行,因此您可以 100% 确定输出将是:

Counter value: 1
Counter value: 2

但绝不会:

Counter value: 2
Counter value: 2

关于c - 一些我无法理解的简单 C 代码 - 互斥锁在这里做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4928838/

相关文章:

c - 使用指向数组的结构体进行队列

编译器认为 struct 是指向 struct 的指针

c - 在子字符串的每个实例中添加一个字符

戈朗 : Values containing the types defined in this package should not be copied

c++ - std::condition_variable 多次调用 notify_all

c - 多次互斥锁定

c++ - 为什么这个双重互斥锁不会造成死锁呢?

c - 编译为 GUI 的 Win32 GUI 应用程序需要使用 C 语言的控制台

multithreading - 如何将 "unlock"设为 RwLock?

c - semget() 函数的标志值