线程同步机制

线程同步机制

Linux 线程同步机制

  • mutexes - Mutual exclusion lock (互斥锁):
  • joins - 让一个线程等待其他线程结束
  • condition variables 条件变量 - 数据类型 pthread_cond_t

1. Mutexes

A mutex is basically a lock that we set (lock) before accessing a shared resource and release (unlock) when we’re done.

1
2
3
4
5
6
7
8
9
10
/* Note scope of variable and mutex are the same */
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter=0;

/* Function C */
void functionC() {
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
}

当使用两个或以上的 Mutexes 的时候,一定要注意防范死锁问题,切记对加锁的顺序问题重点关注。

2. Joins

一个线程等待另外一个线程结束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <pthread.h>

#define NTHREADS 10
void *thread_function(void *);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

main() {
pthread_t thread_id[NTHREADS];
int i, j;

for(i=0; i < NTHREADS; i++) {
pthread_create( &thread_id[i], NULL, thread_function, NULL );
}

for(j=0; j < NTHREADS; j++) {
// 主线程等待 thread_id[j] 结束
pthread_join( thread_id[j], NULL);
}

// 走到这个地方说明所有线程都已经结束了

printf("Final counter value: %d\n", counter);
}

void *thread_function(void *dummyPtr) {
printf("Thread number %ld\n", pthread_self());
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
}

3. Condition Variables

Condition Variables 总是应该和 Mutex 一块使用来避免竞态条件。使用 Condition Variables 的函数:

  • 创建/销毁
    • pthread_cond_init
    • pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    • pthread_cond_destroy
  • 等待一个 Condition
    • pthread_cond_wait
    • pthread_cond_timedwait - 阻塞多久
  • 唤醒在某个 Condition 上的线程
    • pthread_cond_signal
    • pthread_cond_broadcast - 唤醒等待在这个 Condition 上的所有线程
1
2
3
4
5
6
7
8
9
10
11
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;

for(;;) {
// 改变 condition_cond 状态之前,必须先锁住 Mutex
pthread_mutex_lock( &condition_mutex );
while( count >= COUNT_HALT1 && count <= COUNT_HALT2 ) {
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
}

参考

推荐文章