- 论坛徽章:
- 1
|
线程见同步问题:一个数组可以同时写,读的时候需要锁定?
1、线程同步常用的方式有两种,一种是互斥锁。该机制适合于数个线程对共享资源的同时访问所带来的问题。
示例代码如下:
- 。。。。
- pthread_mutexattr_t *attr;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- 。。。。
- if( ( ret = pthread_mutex_init(&mutex ,NULL) ) != 0 ) {
- (void)fprintf(stderr,"pthread_mutex_init error\n");
- return PINIT_FAILED;
- }
- 。。。。
- if( ( ret = pthread_mutex_lock(&mutex ) != 0 ) {
- (void)fprintf(stderr,"pthread_mutex_lock error\n");
- return PLOCK_FAILED;
- }
- /*该处是要保护的资源*/
- 。。。。
- if( ( ret = pthread_mutex_unlock(&mutex ) != 0 ) {
- (void)fprintf(stderr,"pthread_mutex_lock error\n");
- return PUNLOCK_FAILED;
- }
- 。。。
复制代码
需要说明的是对于静态分配的互斥锁,建议做pthread_mutex_init,有些系统并不做初始化的工作。
2、另外常用的一种是条件变量,该机制类似于信号处理,通过阻塞与等待条件变量信号来实现。可参看下面的调用。
pthread_cond_wait
pthread_cond_timedwait
pthread_cond_signal
pthread_cond_broadcast
[/code] |
|