目录
3. 同步
3.1 概念
3.2 同步机制
3.3 函数接口
1. 同步
1.1 概念
同步(synchronization)指的是多个任务(线程)按照约定的顺序相互配合完成一件事情
1.2 同步机制
通过信号量实现线程间的同步
信号量:通过信号量实现同步操作;由信号量来决定线程是继续运行还是阻塞等待.
信号量代表某一类资源,其值表示系统中该资源的数量:
信号量的值>0,表示有资源可以用, 可以申请到资源,
信号量的值<=0, 表示没有资源可以用, 无法申请到资源, 阻塞.
信号量还是一个受保护的变量,只能通过三种操作来访问:初始化、P操作(申请资源)、V操作(释放资源)
sem_init: 信号量初始化
sem_wait: 申请资源,P操作, 如果没有资源可以用, 阻塞,-1
sem_post: 释放资源,V操作, 非阻塞 +1
1.3 函数接口
int sem_init(sem_t *sem, int pshared, unsigned int value) 功能:初始化信号量
参数:sem:初始化的信号量对象pshared:信号量共享的范围(0: 线程间使用 非0:1进程间使用)value:信号量初值
返回值:成功 0失败 -1int sem_wait(sem_t *sem) 功能:申请资源 P操作
参数:sem:信号量对象
返回值:成功 0失败 -1注:此函数执行过程,当信号量的值大于0时,表示有资源可以用,则继续执行,同时对信号量减1;当信号量的值等于0时,表示没有资源可以使用,函数阻塞int sem_post(sem_t *sem) 功能:释放资源 V操作
参数:sem:信号量对象
返回值:成功 0失败 -1注:释放一次信号量的值加1,函数不阻塞
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>sem_t sem;
char str[32];void *handler_thread(void *arg)
{while (1) //输出{//申请资源sem_wait(&sem); //P操作,申请到资源-1,申请不到会阻塞等待着申请资源if (strcmp(str, "quit") == 0)break;printf("%s\n", str);}
}int main(int argc, char const *argv[])
{pthread_t tid;if (pthread_create(&tid, NULL, handler_thread, NULL) != 0){perror("thread create err");return -1;}//信号量初始化if (sem_init(&sem, 0, 0) != 0){perror("sem_init err");return -1;}while (1) //输入{scanf("%s", str);//输入完成之后,释放资源sem_post(&sem); //V操作 +1if (strcmp(str, "quit") == 0)break;}pthread_join(tid,NULL);return 0;
}
两个信号量:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>sem_t sem;
sem_t sem1;
char str[32];void *handler_thread(void *arg)
{while (1) //输出{//申请资源sem_wait(&sem); //P操作,申请到资源-1,申请不到会阻塞等待着申请资源if (strcmp(str, "quit") == 0)break;printf("%s\n", str);sem_post(&sem1);}
}int main(int argc, char const *argv[])
{pthread_t tid;if (pthread_create(&tid, NULL, handler_thread, NULL) != 0){perror("thread create err");return -1;}//信号量初始化if (sem_init(&sem, 0, 0) != 0){perror("sem_init err");return -1;}if (sem_init(&sem1, 0, 1) != 0){perror("sem_init err");return -1;}while (1) //输入{sem_wait(&sem1);scanf("%s", str);//输入完成之后,释放资源sem_post(&sem); //V操作 +1if (strcmp(str, "quit") == 0)break;}pthread_join(tid,NULL);return 0;
}
2. 互斥
2.1 概念
互斥:多个线程在访问临界资源时,同一时间只能一个线程访问
临界资源:一次仅允许一个线所使用的资源
临界区:指的是一个访问共享资源的程序片段
互斥锁:通过互斥锁可以实现互斥机制,主要用来保护临界资源,每个临界资源都由一个互斥锁来保护,线程必须先获得互斥锁才能访问临界资源,访问完资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止。
pthread_mutex_init
pthread_mutex_lock
pthread_mutex_unlock
2.2 函数接口
int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr) 功能:初始化互斥锁
参数:mutex:互斥锁attr: 互斥锁属性 // NULL表示缺省属性
返回值:成功 0失败 -1int pthread_mutex_lock(pthread_mutex_t *mutex) 功能:申请互斥锁
参数:mutex:互斥锁
返回值:成功 0失败 -1注:和pthread_mutex_trylock区别:pthread_mutex_lock是阻塞的;pthread_mutex_trylock不阻塞,如果申请不到锁会立刻返回int pthread_mutex_unlock(pthread_mutex_t *mutex) 功能:释放互斥锁
参数:mutex:互斥锁
返回值:成功 0失败 -1int pthread_mutex_destroy(pthread_mutex_t *mutex) 功能:销毁互斥锁
参数:mutex:互斥锁
例如:打印倒置数组功能
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>int a[10] = {0,1,2,3,4,5,6,7,8,9};
pthread_mutex_t lock;void *handler_swap(void *arg)
{int t;while (1){pthread_mutex_lock(&lock);for(int i=0;i<5;i++){t=a[i];a[i]=a[9-i];a[9-i]=t;}pthread_mutex_unlock(&lock);}return NULL;
}void *handler_printf(void *arg)
{while (1){pthread_mutex_lock(&lock);for (int i = 0; i < 10; i++)printf("%d ",a[i]);printf("\n"); pthread_mutex_unlock(&lock);sleep(1); //互斥锁里面减少耗时大的操作}
}int main(int argc, char const *argv[])
{pthread_t t1,t2;pthread_create(&t1,NULL,handler_swap,NULL);pthread_create(&t2,NULL,handler_printf,NULL);//初始化互斥锁if(pthread_mutex_init(&lock,NULL) != 0){perror("mutex init err");return -1;}pthread_join(t1,NULL);pthread_join(t2,NULL);return 0;
}
补充:死锁
是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。
死锁产生的四个必要条件
1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
3、请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
注意:当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。
3. 条件变量
条件变量用于在线程之间传递信号,以便某些线程可以等待某些条件发生。当某些条件发生时,条件变量会发出信号,使等待该条件的线程可以恢复执行。
一般和互斥锁搭配使用,实现同步机制:
pthread_cond_init(&cond,NULL); //初始化条件变量
使用前需要上锁:
pthread_mutex_lock(&lock); //上锁
判断条件
pthread_cond_wait(&cond, &lock); //阻塞等待条件产生,没有条件产生时阻塞,同时解锁,当条件产生时结束阻塞,再次上锁
pthread_cond_signal(&cond); //产生条件,不阻塞
pthread_cond_destroy(&cond); //销毁条件变量
注意: 必须保证让pthread_cond_wait先执行,pthread_cond_signal再产生条件
为什么pthread_cond_wait前要加互斥锁:防止调用 pthread_cond_wait之前其他线程改变条件,从而发生错乱。
例如:当value满足大于等于0才做某事
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>int value = 0;
pthread_mutex_t lock;
pthread_cond_t cond;//从线程
void *slave(void *arg)
{pthread_mutex_lock(&lock);if (value <= 0) //需要value>0,所以value<=0就是条件不满足,value初值为0{//阻塞等待条件产生,没有条件产生时,阻塞并解锁,当条件产生时结束阻塞,再次上锁。pthread_cond_wait(&cond, &lock);//条件满足,进行相关处理printf("make samething!\n");}pthread_mutex_unlock(&lock);return NULL;
}int main(int argc, char const *argv[])
{pthread_t tid;pthread_create(&tid, NULL, slave, NULL);pthread_mutex_init(&lock, NULL);pthread_cond_init(&cond, NULL);sleep(2); //保证从线程先执行,先pthread_cond_waitpthread_mutex_lock(&lock);scanf("%d", &value);while (value <= 0){value++;printf("%d\n", value);}if (value > 0)pthread_cond_signal(&cond);pthread_mutex_unlock(&lock);pthread_join(tid, NULL);pthread_cond_destroy(&cond);return 0;
}
例如: 赚钱和花钱
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>int money = 0;
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_cond_t cond1;//花钱
void *spend_money(void *arg)
{while (1){pthread_mutex_lock(&lock);if (money < 100) //<100就没钱花了等待赚钱线程赚钱,达到>=100才开始花钱pthread_cond_wait(&cond, &lock);while (money >= 100){money -= 100;printf("money:%d trillion\n", money);}if (money < 100) //花完钱告诉赚钱线程继续下次赚钱pthread_cond_signal(&cond1);pthread_mutex_unlock(&lock);}return NULL;
}int main(int argc, char const *argv[])
{pthread_t tid;pthread_create(&tid, NULL, spend_money, NULL);pthread_mutex_init(&lock, NULL);pthread_cond_init(&cond, NULL);pthread_cond_init(&cond1, NULL);//赚钱while (1){// sleep(1);pthread_mutex_lock(&lock);if (money >= 100) //>=100就不用赚钱了阻塞等待花钱,等花完钱再继续赚钱。pthread_cond_wait(&cond1, &lock);scanf("%d", &money);if (money >= 100) //赚够>=100的钱就告诉花钱线程去花钱pthread_cond_signal(&cond);pthread_mutex_unlock(&lock);}return 0;
}