参考引用
以上 3 点中,前两点不能改变,欲提高效率,传递数据时资源必须共享。只要共享资源,就一定会出现竞争只要存在竞争关系,数据就很容易出现混乱。所以只能从第 3 点着手解决,使多个线程在访问共享资源的时候出现互斥
#include
// 返回值都是: 成功返回 0,失败返回错误号
// pthread_mutex_t 类型,其本质是一个结构体
// pthread_mutex_t mutex; 变量 mutex 只有两种取值 1、0
// 初始化一个互斥锁(互斥量) --> 初值可看作 1
// 参 1: 传出参数,调用时应传 &mutex
// restrict 用来限定指针变量。被该关键字限定的指针变量所指向的内存操作,必须由本指针完成
// 参 2: 互斥量属性。是一个传入参数,通常传 NULL,选用默认属性(线程间共享)
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
// 销毁一个互斥锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);
// 加锁。可理解为将 mutex-- (或 -1),操作后 mutex 的值为 0
int pthread_mutex_lock(pthread_mutex_t *mutex);
// 解锁。可理解为将 mutex++ (或 +1),操作后 mutex 的值为 1
int pthread_mutex_unlock(pthread_mutex_t *mutex);
// 尝试加锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);
#include
#include
#include
#include
#include
#include
pthread_mutex_t mutex; // 定义一把全局互斥锁
void *tfn(void *arg) {
srand(time(NULL));
while(1) {
pthread_mutex_lock(&mutex); // 加锁,为 0
printf("hello ");
sleep(rand() % 3); // 模拟长时间操作共享资源,导致 cpu 易主,产生与时间有关的错误
printf("world\n");
pthread_mutex_unlock(&mutex); // 解锁,为 1
sleep(rand() % 3);
}
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t tid;
srand(time(NULL));
int ret = pthread_mutex_init(&mutex, NULL); // 初始化互斥锁,为 1
if (ret != 0) {
fprintf(stderr, "mutex init error: %s\n", strerror(ret));
exit(1);
}
pthread_create(&tid, NULL, tfn, NULL);
while (1) {
pthread_mutex_lock(&mutex); // 加锁
printf("HELLO ");
sleep(rand() % 3);
printf("WORLD\n");
pthread_mutex_unlock(&mutex); // 解锁
sleep(rand() % 3);
}
pthread_join(tid, NULL);
pthread_mutex_destroy(&mutex); // 销毁互斥锁
return 0;
}
$ gcc pthread_shared.c -o pthread_shared -pthread
$ ./pthread_shared
HELLO WORLD
hello world
HELLO WORLD
...
#include
#include
#include
#if 1
int var = 1, num = 5;
pthread_mutex_t m_var, m_num;
void *tfn(void *arg) {
int i = (int)arg;
if (i == 1) {
pthread_mutex_lock(&m_var);
var = 22;
sleep(1); //给另外一个线程加锁,创造机会.
pthread_mutex_lock(&m_num);
num = 66;
pthread_mutex_unlock(&m_var);
pthread_mutex_unlock(&m_num);
printf("----thread %d finish\n", i);
pthread_exit(NULL);
} else if (i == 2) {
pthread_mutex_lock(&m_num);
var = 33;
sleep(1);
pthread_mutex_lock(&m_var);
num = 99;
pthread_mutex_unlock(&m_var);
pthread_mutex_unlock(&m_num);
printf("----thread %d finish\n", i);
pthread_exit(NULL);
}
return NULL;
}
int main(void) {
pthread_t tid1, tid2;
int ret1, ret2;
pthread_mutex_init(&m_var, NULL);
pthread_mutex_init(&m_num, NULL);
pthread_create(&tid1, NULL, tfn, (void *)1);
pthread_create(&tid2, NULL, tfn, (void *)2);
sleep(3);
printf("var = %d, num = %d\n", var, num);
ret1 = pthread_mutex_destroy(&m_var); //释放琐
ret2 = pthread_mutex_destroy(&m_num);
if (ret1 == 0 && ret2 == 0)
printf("------------destroy mutex finish\n");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("------------join thread finish\n");
return 0;
}
#else
int a = 100;
int main(void) {
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
a = 777;
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
printf("-----------a = %d\n", a);
pthread_mutex_destroy(&mutex);
return 0;
}
#endif
$ gcc deadlock.c -o deadlock -pthread
$ ./deadlock
var = 33, num = 5
...
读写锁非常适合于对数据结构读的次数远大于写的情况
#include
// 返回值 成功返回 0,失败直接返回错误号
// 初始化一把读写锁
// 参 2: attr 表读写锁属性,通常使用默认属性,传 NULL 即可
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
// 销毁一把读写锁
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
// 以读方式请求读写锁 (简称:请求读锁)
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
// 非阻塞以读方式请求读写锁 (非阻塞请求读锁)
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
// 以写方式请求读写锁 (简称:请求写锁)
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
// 非阻塞以写方式请求读写锁 (非阻塞请求写锁)
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
// 解锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
#include
#include
#include
int counter; // 全局资源
pthread_rwlock_t rwlock;
void *th_write(void *arg) {
int t;
int i = (int)arg;
while (1) {
t = counter; // 保存写之前的值
usleep(1000);
pthread_rwlock_wrlock(&rwlock);
printf("=======write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter);
pthread_rwlock_unlock(&rwlock);
usleep(9000); // 给 r 锁提供机会
}
return NULL;
}
void *th_read(void *arg) {
int i = (int)arg;
while (1) {
pthread_rwlock_rdlock(&rwlock);
printf("----------------------------read %d: %lu: %d\n", i, pthread_self(), counter);
pthread_rwlock_unlock(&rwlock);
usleep(2000); // 给写锁提供机会
}
return NULL;
}
int main(void) {
int i;
pthread_t tid[8];
pthread_rwlock_init(&rwlock, NULL);
for (i = 0; i < 3; i++)
pthread_create(&tid[i], NULL, th_write, (void *)i);
for (i = 0; i < 5; i++)
pthread_create(&tid[i+3], NULL, th_read, (void *)i);
for (i = 0; i < 8; i++)
pthread_join(tid[i], NULL);
pthread_rwlock_destroy(&rwlock); // 释放读写琐
return 0;
}
$ gcc rwlock.c -o rwlock -pthread
$ ./rwlock
----------------------------read 0: 140472231028480: 0
----------------------------read 3: 140472205850368: 0
----------------------------read 2: 140472214243072: 0
----------------------------read 4: 140472197457664: 0
----------------------------read 1: 140472222635776: 0
=======write 0: 140472256206592: counter=0 ++counter=1
=======write 1: 140472247813888: counter=0 ++counter=2
=======write 2: 140472239421184: counter=0 ++counter=3
----------------------------read 2: 140472214243072: 3
----------------------------read 3: 140472205850368: 3
...
#include
// 返回值 成功返回 0,失败直接返回错误号
// 初始化一个条件变量
// 参 2: attr 表条件变量属性,通常为默认值,传 NULL 即可
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
// 销毁一个条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
// 函数作用(1、2 两步为一个原子操作)
// 1、阻塞等待条件变量 cond (参 1) 满足
// 2、释放已掌握的互斥锁 (解锁互斥量),相当于 pthread_mutex_unlock(&mutex);
// 3、当被唤醒,pthread_cond_wait 函数返回时,解除阻塞并重新申请获取互斥锁 pthread_mutex_lock(&mutex);
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
// 限时等待一个条件变量
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
// 唤醒至少一个阻塞在条件变量上的线程
int pthread_cond_signal(pthread_cond_t *cond);
// 唤醒全部阻塞在条件变量上的线程
int pthread_cond_broadcast(pthread_cond_t *cond);
#include
#include
#include
#include
#include
#include
void err_thread(int ret, char *str) {
if (ret != 0) {
fprintf(stderr, "%s:%s\n", str, strerror(ret));
pthread_exit(NULL);
}
}
struct msg {
int num;
struct msg *next;
};
struct msg *head;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 定义/初始化一个互斥量
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER; // 定义/初始化一个条件变量
void *produser(void *arg) {
while (1) {
struct msg *mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1; // 模拟生产一个数据`
printf("--produce %d\n", mp->num);
pthread_mutex_lock(&mutex); // 加锁 互斥量
mp->next = head; // 写公共区域
head = mp;
pthread_mutex_unlock(&mutex); // 解锁 互斥量
pthread_cond_signal(&has_data); // 唤醒阻塞在条件变量 has_data上的线程.
sleep(rand() % 3);
}
return NULL;
}
void *consumer(void *arg) {
while (1) {
struct msg *mp;
pthread_mutex_lock(&mutex); // 加锁 互斥量
while (head == NULL) {
pthread_cond_wait(&has_data, &mutex); // 阻塞等待条件变量, 解锁
} // pthread_cond_wait 返回时, 重新加锁 mutex
mp = head;
head = mp->next;
pthread_mutex_unlock(&mutex); // 解锁 互斥量
printf("---------consumer id: %lu :%d\n", pthread_self(), mp->num);
free(mp);
sleep(rand()%3);
}
return NULL;
}
int main(int argc, char *argv[]) {
int ret;
pthread_t pid, cid;
srand(time(NULL));
ret = pthread_create(&pid, NULL, produser, NULL); // 生产者
if (ret != 0)
err_thread(ret, "pthread_create produser error");
ret = pthread_create(&cid, NULL, consumer, NULL); // 消费者
if (ret != 0)
err_thread(ret, "pthread_create consuer error");
ret = pthread_create(&cid, NULL, consumer, NULL); // 消费者
if (ret != 0)
err_thread(ret, "pthread_create consuer error");
ret = pthread_create(&cid, NULL, consumer, NULL); // 消费者
if (ret != 0)
err_thread(ret, "pthread_create consuer error");
pthread_join(pid, NULL);
pthread_join(cid, NULL);
return 0;
}
$ gcc cond.c -o cond -pthread
$ ./cond
--produce 208
---------consumer id: 140611653785344 :208
--produce 829
---------consumer id: 140611645392640 :829
--produce 191
--produce 625
---------consumer id: 140611662178048 :625
---------consumer id: 140611653785344 :191
--produce 926
---------consumer id: 140611645392640 :926
...
信号量相当于初始化值为 N 的互斥量
信号量,是相对折中的一种处理方式,既能保证同步,数据不混乱,又能提高线程并发
#include
// 返回值 成功返回 0,失败返回-1,同时设置 errno
// 规定信号量 sem 不能 < 0
// 初始化一个信号量
// 参 1: sem 信号量
// 参 2: pshared 取 0 用于线程间; 取非 (一般为 1) 用于进程间
// 参 3: value 指定信号量初值
int sem_init(sem_t *sem, int pshared, unsigned int value);
// 销毁一个信号量
int sem_destroy(sem_t *sem);
// 给信号量加锁 --
int sem_wait(sem_t *sem);
// 尝试对信号量加锁 -- (与 sem_wait 的区别类比 lock 和 trylock)
int sem_trywait(sem_t *sem);
// 限时尝试对信号量加锁 --
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
// 给信号量解锁 ++
int sem_post(sem_t *sem);
/*信号量实现 生产者 消费者问题*/
#include
#include
#include
#include
#include
#define NUM 5
int queue[NUM]; // 全局数组实现环形队列
sem_t blank_number, product_number; // 空格子信号量, 产品信号量
void *producer(void *arg) {
int i = 0;
while (1) {
sem_wait(&blank_number); // 生产者将空格子数--,为0则阻塞等待
queue[i] = rand() % 1000 + 1; // 生产一个产品
printf("----Produce---%d\n", queue[i]);
sem_post(&product_number); // 将产品数++
i = (i+1) % NUM; // 借助下标实现环形
sleep(rand()%1);
}
}
void *consumer(void *arg) {
int i = 0;
while (1) {
sem_wait(&product_number); // 消费者将产品数--,为0则阻塞等待
printf("-Consume---%d\n", queue[i]);
queue[i] = 0; // 消费一个产品
sem_post(&blank_number); // 消费掉以后,将空格子数++
i = (i+1) % NUM;
sleep(rand()%3);
}
}
int main(int argc, char *argv[]) {
pthread_t pid, cid;
sem_init(&blank_number, 0, NUM); // 初始化空格子信号量为5, 线程间共享 -- 0
sem_init(&product_number, 0, 0); // 产品数为 0
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&blank_number);
sem_destroy(&product_number);
return 0;
}
$ gcc sem.c -o sem -pthread
$ ./sem
----Produce---384
-Consume---384
----Produce---916
-Consume---916
...