1 信号量和PV操作
信号量
- 信号量(Semaphore)是一种比互斥锁更强大的同步 工具,它可以提供更高级的方法来同步并发进程。
- 一个信号量S是一个整数变量,除了初始化,只能被两个原子操作修改:P和V。
- P:wait() operation
- V:signal() operation
**信号量的实现 **
2 信号量的使用
二值信号量
- 顾名思义,二值信号量的值只能是0或1,通常将其 初始化为1,用于实现互斥锁的功能。
一般信号量
- 一般信号量的取值可以是任意数值,用于控制并发 进程对共享资源的访问。
3 实践
- 生产者和消费者共享1个缓冲区,使用之前学过的方法创建两个线程分别作为生产者和消费者。创建新的源代码文件producerAndConsumer.c,内容如下:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t empty;
sem_t full;
void* producerThd(void* arg){
for(int i=0; i<10; i++){
printf("**Producing one item.**\n");
sem_wait(&empty);
printf("**PUTTING item to warehouse.**\n");
sem_post(&full);
}
pthread_exit(0);
}
void* consumerThd(void* arg){
for(int i=0; i<10; i++){
sem_wait(&full);
printf("##GETTING item from warehouse.##\n");
sem_post(&empty);
printf("##Consuming the item.##\n");
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t producer_tid, consumer_tid;
sem_init(&empty, 0, 1);
sem_init(&full, 0, 0);
pthread_create(&producer_tid, NULL, producerThd, NULL);
pthread_create(&consumer_tid, NULL, consumerThd, NULL);
pthread_join(producer_tid, NULL);
pthread_join(consumer_tid, NULL);
sem_destroy(&empty);
sem_destroy(&full);
}
使用下面的命令进行编译生成可执行文件,然后运行程序。
gccproducerAndConsumer.c-oproducerAndConsumer-lpthread
- 代码说明:
- 要使用信号量,请先包含头文件<semaphore.h>
- sem_t:信号量的数据类型
- int sem_init(sem_t *sem, int pshared, unsigned int val);
该函数第一个参数为信号量指针,第二个参数为信号量类型(一般设置为0),第三个为信号量初始值。第二个参数pshared为0时,该进程内所有线程可用,不为0时不同进程间可用。 - int sem_wait(sem_t *sem);
该函数申请一个信号量,当前无可用信号量则等待,有可用信号量时占用一个信号量,对信号量的值减1。 - int sem_post(sem_t *sem);
该函数释放一个信号量,信号量的值加1。 - int sem_destory(sem_t *sem);
该函数销毁信号量。
- 当生产者和消费者共享多个缓冲区时,设Bank[10]为仓库,有10个位置放置商品,元素为0表示为空,为1时表示有商品,除了要用信号量同步外,还要加入互斥操作保护临界区,代码如下。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
void printBank();
sem_t empty;
sem_t full;
int Bank[10]={0};
int in=0,out=0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* producerThd(void* arg){
for(int i=0; i<20; i++){
sem_wait(&empty);
pthread_mutex_lock(&lock); //临界区开始
Bank[in] = 1;
in = (in+1)%10;
printBank();
sleep(0.1);
pthread_mutex_unlock(&lock);//临界区结束
sem_post(&full);
}
pthread_exit(0);
}
void* consumerThd(void* arg){
for(int i=0; i<20; i++){
sem_wait(&full);
pthread_mutex_lock(&lock); //临界区开始
Bank[out] = 0;
out = (out+1)%10;
printBank();
sleep(1);
pthread_mutex_unlock(&lock);//临界区结束
sem_post(&empty);
}
pthread_exit(0);
}
/*该函数用以输出缓冲区的全部数值*/
void printBank(){
printf("Bank:");
for(int i=0; i<10; i++){
printf("[%d]",Bank[i]);
if(i==9) putchar('\n');
}
}
int main(int argc, char *argv[]) {
pthread_t producer_tid, consumer_tid;
sem_init(&empty, 0, 10);
sem_init(&full, 0, 0);
pthread_create(&producer_tid, NULL, producerThd, NULL);
pthread_create(&consumer_tid, NULL, consumerThd, NULL);
pthread_join(producer_tid, NULL);
pthread_join(consumer_tid, NULL);
sem_destroy(&empty);
sem_destroy(&full);
}
在该步实验中,我们用sleep()来调节生产和消费的速度,我们故意让生产比消费快一点,这样我们可以更好地观察运行结果。