《Linux操作系统》实验3:线程信号量同步与互斥

一、实验目的

通过本实验的练习,熟悉如何使用信号量实现线程间的同步。

二、实验方法

  1. 掌握信号量的创建及初始化函数的调用方法;
  2. 掌握PV操作对应的POSIX信号量函数的调用方法;
  3. 解决经典的生产和消费者问题;
  4. 解决其他同步问题。

三、实验内容

  1. 订票系统(临界区的管理)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int ticketAmount = 2; //Global Variable
void* ticketAgent(void* arg){
int t = ticketAmount;
//sleep(1);
if (t > 0)
{
printf("One ticket sold!\n");
t--;
}else{
printf("Ticket sold out!!\n");
}
ticketAmount = t;
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
pthread_t ticketAgent_tid[2];
for (int i = 0; i < 2; ++i)
{
pthread_create(ticketAgent_tid+i, NULL, ticketAgent,NULL);
}
for (int i = 0; i < 2; ++i)
{
pthread_join(ticketAgent_tid[i],NULL);
}
printf("The left ticket is %d\n", ticketAmount);
return 0;
}

该份代码用一个线程函数创建了两个线程,这种创建方法可以使用循环来减少代码的书写量(23行至28行),30行至33行学习如何用循环来等待所有线程结束。两个线程作为售票终端共享一个全局变量ticketAmount,两个线程运行结束后在主线程中打印余票量,编译运行这份代码,观察结果。
然后找出临界区,用互斥锁对临界区进行管理,阅读并运行下面的代码。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int ticketAmount = 2; //Global Variable
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; //Global lock
void* ticketAgent(void* arg){
pthread_mutex_lock(&lock);
int t = ticketAmount;
if (t > 0)
{
printf("One ticket sold!\n");
t--;
}else{
printf("Ticket sold out!!\n");
}
ticketAmount = t;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
pthread_t ticketAgent_tid[2];
for (int i = 0; i < 2; ++i)
{
pthread_create(ticketAgent_tid+i, NULL, ticketAgent,NULL);
}
for (int i = 0; i < 2; ++i)
{
pthread_join(ticketAgent_tid[i],NULL);
}
printf("The left ticket is %d\n", ticketAmount);
return 0;
}
代码说明:
a. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; //创建一个互斥锁
b. pthread_mutex_lock(&lock); //上锁
c. pthread_mutex_unlock(&lock); //开锁
  1. 生产者和消费者共享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);
}

使用下面的命令进行编译生成可执行文件,然后运行程序。

gcc producerAndConsumer.c -o producerAndConsumer -l pthread
  1. 代码说明:
    1. 要使用信号量,请先包含头文件<semaphore.h>
    2. sem_t:信号量的数据类型
    3. int sem_init(sem_t *sem, int pshared, unsigned int val);
      该函数第一个参数为信号量指针,第二个参数为信号量类型(一般设置为0),第三个为信号量初始值。第二个参数pshared为0时,该进程内所有线程可用,不为0时不同进程间可用。
    4. int sem_wait(sem_t *sem);
      该函数申请一个信号量,当前无可用信号量则等待,有可用信号量时占用一个信号量,对信号量的值减1。
    5. int sem_post(sem_t *sem);
      该函数释放一个信号量,信号量的值加1。
    6. int sem_destory(sem_t *sem);
      该函数销毁信号量。
  2. 当生产者和消费者共享多个缓冲区时,设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()来调节生产和消费的速度,我们故意让生产比消费快一点,这样我们可以更好地观察运行结果。
4. 采用信号量机制,解决苹果橙子问题:一个能放N(这里N设为3)个水果的盘子,爸爸只往盘子里放苹果,妈妈只放橙子,女儿只吃盘子里的橙子,儿子只吃苹果。采用三个信号量:

  1. sem_t empty:信号量empty控制盘子可放水果数,初始为3,因为开始盘子为空可放水果数为3。
  2. sem_t apple ;信号量apple控制儿子可吃的苹果数,初始为0,因为开始盘子里没苹果。
  3. sem_t orange;信号量orange控制女儿可吃的橙子是,初始为0,因为开始盘子里没橙子。
  4. 互斥量work_mutex为printf输出时能够保持一致。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t empty; //
sem_t apple; //
sem_t orange; //
pthread_mutex_t work_mutex=PTHREAD_MUTEX_INITIALIZER; //work_mutex
int fruitCount = 0;//
void *procf(void *arg) //father线
{
while(1){
sem_wait(&empty); //1
pthread_mutex_lock(&work_mutex); //
printf("!%d\n", ++fruitCount);
sem_post(&apple); //apple1
pthread_mutex_unlock(&work_mutex); //
sleep(0.1);
}
}
void *procm(void *arg) //mother线
{
while(1){
sem_wait(&empty);
pthread_mutex_lock(&work_mutex); //
printf("!%d\n", ++fruitCount);
sem_post(&orange);
pthread_mutex_unlock(&work_mutex); //
sleep(0.2);
}
}
void *procs(void *arg) //son线
{
while(1){
sem_wait(&apple); //1
pthread_mutex_lock(&work_mutex); //
printf("!%d\n", --fruitCount);
sem_post(&empty); //1
pthread_mutex_unlock(&work_mutex); //
sleep(0.2);
}
}
void *procd(void *arg) //daughter线
{
while(1){
sem_wait(&orange);
pthread_mutex_lock(&work_mutex); //
printf("!%d\n", --fruitCount);
sem_post(&empty);
pthread_mutex_unlock(&work_mutex); //
sleep(0.1);
}
}
int main()
{
pthread_t father; //线
pthread_t mother;
pthread_t son;
pthread_t daughter;
sem_init(&empty, 0, 3); //
sem_init(&apple, 0, 0);
sem_init(&orange, 0, 0);
pthread_create(&father,NULL,procf,NULL); //线
pthread_create(&mother,NULL,procm,NULL);
pthread_create(&daughter,NULL,procd,NULL);
pthread_create(&son,NULL,procs,NULL);
sleep(1);
sem_destroy(&empty);
sem_destroy(&apple);
sem_destroy(&orange);
return 0;
}
  1. 课外实验。请自行写一份代码,可以实现课堂PPT中所述司机和售票员的同步过程,实验效果请参见视频。
  2. 备注:本次实验内容有完整教学视频,请自行在云盘下载。