互斥锁
//定义互斥锁
pthread_t mutex;
//初始化
int pthread_mutex_init(&mutex, NULL);
//锁和解锁
int pthread_mutex_lock(&mutex);
int pthread_mutex_unlock(&mutex);
//销毁
int pthread_mutex_destroy(&mutex);
条件变量
线程可用的另一种同步机制,条件变量与互斥量一起使用,由互斥量保护。
传递给pthread_cond_wait的互斥量对条件进行保护。调用者把锁住的互斥量传给函数,函数把调用线程放在等待条件的线程列表,然后对互斥量解锁。条件满足后,函数返回时,对互斥量加锁。
pthread_cond_t cond;
//初始化
int pthread_cond_init(&cond, NULL);
//等待条件
int pthread_cond_wait(&cond, &mutex);
//发送条件满足信号
int pthread_cond_signal(&cond);
//销毁
int pthread_cond_destroy(&cond);
读写锁
与互斥量类似,但是有更高的并行性。
三种状态:读模式加锁,写模式加锁,不加锁。
写模式加锁,其他线程只能阻塞,直到解锁。
读模式加锁,其他线程读时,可以加锁,读,不会阻塞,但是写的线程会被阻塞。当有写的线程阻塞时,其他打算来读的线程也会被阻塞,直到正在读的线程读完,然后写的线程写完,等待读的线程才会读。这样有效避免读模式锁长期占用,而等待的写模式锁一直得不到满足。
pthread_rwlock_t rwlock;
int pthread_rwlock_init(&rwlock, NULL);
//读锁
int pthread_rwlock_rdlock(&rwlock);
//写锁
int pthread_rwlock_wrlock(&rwlock);
//解锁
int pthread_rwlock_unlock(&rwlock);
//销毁
int pthread_rwlock_destroy(&rwlock);
自旋锁
不通过休眠等待,一直忙等,一直占用CPU,适合需要实时的情况
pthread_spin_t spin;
int pthread_spin_init(&spin, NULL);
//未获取到锁资源,一直自旋
int pthread_spin_lock(&spin);
//未获取到锁资源,返回EBUSY错误
int pthread_spin_trylock(&spin);
int pthread_spin_unlock(&spin);
int pthread_spin_destroy(&spin);
不要调用在持有自旋锁情况可能会进入休眠的函数,会造成CPU的浪费。
生产者消费者
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int arr[10] = {0};
void* consumer(void* argv)
{
int i = 0;
while(1)
{
usleep(500000);
printf("xiaofei wait>>%d %d\n", i, arr[i]);
pthread_mutex_lock(&mutex);
while(arr[i] == 0)
pthread_cond_wait(&cond, &mutex);
arr[i]--;
printf("xiaofei OK>>%d %d\n", i, arr[i]);
i++;
i %= 10;
pthread_mutex_unlock(&mutex);
}
}
void* producer(void* argv)
{
int i = 0;
while(1)
{
usleep(50000);
printf("shenchan wait>>%d %d\n", i, arr[i]);
if(arr[i] == 0)
{
pthread_mutex_lock(&mutex);
arr[i]++;
printf("shenchan OK>>%d %d\n", i, arr[i]);
i++;
i %= 10;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
}
}
int main()
{
pthread_t consumer_tid;
pthread_t producer_tid;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&consumer_tid, NULL, consumer, NULL);
pthread_create(&producer_tid, NULL, producer, NULL);
pthread_join(consumer_tid, NULL);
pthread_join(producer_tid, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}