线程间通信

锁机制

互斥锁

同一时间只有一个线程访问数据。互斥锁采用pthread_mutex_t数据类型表示,常用API包括:


API

 

pthread_mutex_init

 

pthread_mutex_destroy

 

pthread_mutex_lock

 

pthread_mutex_trylock

 

pthread_mutex_unlock

 



读写锁

读写锁有三个状态:读模式下加锁状态,写模式下加锁状态,不加锁状态。一次只有一个线程可以占有写模式的读写锁,但是多个线程可以同时占有读模式的读写锁。

当读写锁是写加锁状态时,在这个锁被解锁前,所有试图对这个锁加锁(读或写)的线程都会被阻塞。当读写锁是读加锁状态时,所有试图以读模式对它进行加锁的线程都可以得到访问权限,但是如果线程希望以写模式对此锁进行加锁,它必须阻塞直到所有的线程释放读锁。

API

 

pthread_rwlock_init

 

pthread_rwlock _destroy

 

pthread_rwlock_rdlock

 

pthread_rwlock_rwlock

 

pthread_rwlock_tryrdlock

 

pthread_rwlock_tryrwlock

 

pthread_rwlock_unlock

 




条件变量

条件变量与互斥锁一起使用,允许线程以无竞争的方式等待特定的条件发生。

条件本身是由互斥锁保护的。线程在改变条件前必须首先锁住互斥锁,其它线程在获取互斥锁前是不会察觉到这种改变的,因为必须锁定互斥锁以后才能计算条件。


API

 

pthread_cond_init

 

pthread_cond_destroy

 

pthread_cond_wait

1.       调用该函数前先加锁互斥量;

2.       调用该函数后,函数把调用线程放到等待条件的线程列表上;

3.       然后对互斥锁解锁;

4.       该函数返回时,互斥锁再次被锁住。

pthread_cond_timedwait

 

pthread_cond_signal

一次只有一个等待该条件变量的线程被唤醒

pthread_cond_broadcast

所有等待该条件变量的线程被唤醒


线程间通信

信号量机制

API

 

int sem_init(sem_t *sem, int pshared, unsigned int value);

man sem_init

 

If pshared has the value 0, then the semaphore is shared between the threads of a process, and should be located at some address that is visible to all threads.

 

If  pshared  is  non-zero,  then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)).  (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.)  Any  process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc.

sem_destroy

 

sem_wait

 

sem_trywait

 

sem_timedwait

 

sem_post

 

sem_getvalue

 

 

 


线程间通信

信号机制

一个线程向其它线程发送信号实现通信。