以下代码取自该站点,它显示了如何使用互斥锁。它同时实现了 pthread_join 和 pthread_mutex_lock:
#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(EXIT_SUCCESS);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
我按原样运行了上面给出的代码,它产生了以下结果:
计数器值:1
计数器值:2
但在第二次运行中,我删除了“pthread_mutex_lock(&mutex1);” 和“pthread_mutex_unlock(&mutex1);” . 我编译并运行了代码,它再次产生了相同的结果。
现在让我感到困惑的是为什么在上面的代码中使用互斥锁,而没有它可以完成同样的事情(使用 pthread_join)?如果 pthread_join 阻止另一个线程运行,直到第一个线程完成,那么我认为它已经阻止了另一个线程访问计数器值。pthread_mutex_lock 的目的是什么?