【发布时间】:2011-02-08 10:01:22
【问题描述】:
抱歉,刚刚在这里找到了这段代码 - http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html,并且用这段代码解释了互斥锁,但它让我有点不知所措。我了解互斥锁的功能,并且它在其关键部分保护共享变量。这里的细节让我感到困惑!据我了解,我们正在使用 pthread_create 创建一个新线程,它正在运行 functionC 进程,该进程会增加一个计数器。计数器是受保护的变量,并且由于两个函数同时运行,如果计数器不受互斥锁保护,它会返回错误的值。
这是正确的/关闭的吗?非常感谢:)。
#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 );
}
【问题讨论】: