Qan*_*asi 0 mutex pthreads pthread-join ubuntu-12.04
以下代码是从此站点获取的,并且显示了如何使用互斥锁。它同时实现了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 );
}
Run Code Online (Sandbox Code Playgroud)
我按原样运行了上面的代码,并产生了以下结果:
计数器值:1
计数器值:2
但是在第二次运行中,我删除了“ pthread_mutex_lock(&mutex1);”。和“ pthread_mutex_unlock(&mutex1);” 。我编译并运行了代码,它再次产生了相同的结果。
现在让我感到困惑的是为什么在没有代码的情况下(如果使用pthread_join)可以完成相同的操作,为什么在上面的代码中使用了互斥锁?如果pthread_join阻止另一个线程运行直到第一个线程完成,那么我认为它将已经阻止另一个线程访问计数器值。pthread_mutex_lock的目的是什么?
联接阻止启动线程运行(从而终止进程),直到线程1和线程2完成。它在线程1和线程2 之间不提供任何同步。互斥锁可防止线程1在修改线程2时读取线程1,反之亦然。
如果没有互斥锁,最明显的问题就是线程1和线程2可以完美同步运行。它们每个都从计数器读取零,每个都加一个,然后输出“计数器值:1”。
| 归档时间: |
|
| 查看次数: |
743 次 |
| 最近记录: |