一、线程同步
1. 线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进
行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处
于等待状态。
2. 临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是
同时访问同一共享资源的其他线程不应终端该片段的执行。
3. 线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便捷的共享是有代价
的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程
修改的变量。
以下代码为售票代码,在使用多个子线程的时候,子线程可能同时会对一块内存进行访问,导致卖同一张票,这就引发了线程同步的问题。
// 线程同步
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局变量,线程共享一份资源
int tickets = 100;
void * sellticket(void * arg){// 卖票usleep(6000); // 会导致卖同一张while(tickets>0){printf("%ld 正在卖第 %d 张门票\n" , pthread_self(),tickets);tickets--;}return NULL;
}int main(){// 创建三个子线程pthread_t tid1, tid2, tid3;// sellticket为子线程执行程序pthread_create(&tid1,NULL,sellticket,NULL);pthread_create(&tid2,NULL,sellticket,NULL);pthread_create(&tid3,NULL,sellticket,NULL);// 回收子线程的资源,阻塞pthread_join(tid1,NULL);pthread_join(tid2,NULL);pthread_join(tid3,NULL);// 设置线程分离
// pthread_detach(tid1);
// pthread_detach(tid2);
// pthread_detach(tid3);// 退出主线程,不会影响子线程pthread_exit(NULL);
}
二、 互斥锁
互斥量(Mutex):
- 互斥量是一种同步机制,用于保护临界区,确保在同一时刻只有一个线程能够进入临界区。
- 互斥量通过提供一个锁来实现,线程在进入临界区前必须先获取互斥锁,进入后执行相应的操作,最后释放互斥锁,这样其他线程才能进入。
- 在多线程环境中,使用互斥量可以有效地防止多个线程同时访问共享的临界资源,从而保证数据的一致性和完整性。
1. 为避免线程更新共享变量时出现问题,可以使用互斥量(mutex 是 mutual exclusion 的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共 享资源的原子访问。
2.互斥量有两种状态:已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一
个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报
错失败,具体取决于加锁时使用的方法。
3. 一旦 线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情
况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问
同一资源时将采用如下协议:
⚫ 针对共享资源锁定互斥量⚫ 访问共享资源⚫ 对互斥量解锁
使用互斥锁的线程同步卖票代码
/*互斥量的类型 pthread_mutex_tint pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);- 初始化互斥量- 参数 :- mutex : 需要初始化的互斥量变量- attr : 互斥量相关的属性,NULL- restrict : C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。pthread_mutex_t *restrict mutex = xxx;pthread_mutex_t * mutex1 = mutex;int pthread_mutex_destroy(pthread_mutex_t *mutex);- 释放互斥量的资源int pthread_mutex_lock(pthread_mutex_t *mutex);- 加锁,阻塞的,如果有一个线程加锁了,那么其他的线程只能阻塞等待int pthread_mutex_trylock(pthread_mutex_t *mutex);- 尝试加锁,如果加锁失败,不会阻塞,会直接返回。int pthread_mutex_unlock(pthread_mutex_t *mutex);- 解锁*/#include <stdio.h>
#include <pthread.h>
#include <unistd.h>// 全局变量,所有的线程都共享这一份资源。
int tickets = 10000;// 创建一个互斥量
pthread_mutex_t mutex;void * sellticket(void * arg) {// 卖票while(1) {// 加锁pthread_mutex_lock(&mutex);if(tickets > 0) {usleep(6000);printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);tickets--;}else {// 解锁pthread_mutex_unlock(&mutex);break;}// 解锁pthread_mutex_unlock(&mutex);}return NULL;
}int main() {// 初始化互斥量pthread_mutex_init(&mutex, NULL);// 创建3个子线程pthread_t tid1, tid2, tid3;pthread_create(&tid1, NULL, sellticket, NULL);pthread_create(&tid2, NULL, sellticket, NULL);pthread_create(&tid3, NULL, sellticket, NULL);// 回收子线程的资源,阻塞pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_join(tid3, NULL);pthread_exit(NULL); // 退出主线程// 释放互斥量资源pthread_mutex_destroy(&mutex);return 0;
}