信号量是一种进程同步工具,可以同步并发进程,相较于互斥锁,可以解决更多类型的同步问题(同步即是指进程之间有序执行,而异步是指随机执行)。
信号量是一个整数值,除了初始化其他时间内只能通过PV操作改变其值。信号量通过两个操作来实现,分别命名为P操作和V操作。其中P操作是指等待(wait operation),V操作是指信号数量增加(signal operation)。这两种操作均为原子操作。
p(s){while(s<=0)do nothing;s--;
}v(s){s++;
}
(1)信号量取值为0或1用于实现互斥锁的作用
semaphore mutex = 1;process pi{p(mutex);critical sectionv(mutex);
}
(2)信号量取值为大于1,一般信号量可以取任意值,可以控制并发进程对共享资源的访问,用于表示可控资源的数量。
semaphore road = 2;process Carsi{p(road);pass the fork in the roadv(road);
}
(3)初始值设置为0则用于进程同步。
司机:启动车辆->正常行车->到站停车
售票员:关车门->售票->开车门
规则:司机要等车门关闭才能开车 售票员要等车停下才能开门
//
// driver_conductor.c
//
//
// Created by YIN on 2021/5/16.
//#include "driver_conductor.h"
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <dispatch/dispatch.h>dispatch_semaphore_t d;
dispatch_semaphore_t c;/*司机:启动车辆;正常行车;到站停车。售票:关车门;售票;开车门。*/void* driver(void* args)
{dispatch_semaphore_wait(d, DISPATCH_TIME_FOREVER);printf("Start the vehiclen");printf("Normal drivingn");printf("Stop at the stationn");dispatch_semaphore_signal(c);
}void* conductor(void* args)
{printf("Close the car doorn");dispatch_semaphore_signal(d);printf("Ticket salesn");dispatch_semaphore_wait(c, DISPATCH_TIME_FOREVER);printf("Open the car doorn");
}int main(int argc, char const *argv[])
{pthread_t pid_driver;pthread_t pid_conductor;dispatch_semaphore_t *sem_d = &d;*sem_d = dispatch_semaphore_create(0);dispatch_semaphore_t *sem_c = &c;*sem_c = dispatch_semaphore_create(0);pthread_create(&pid_driver, NULL, driver, NULL);pthread_create(&pid_conductor, NULL, conductor, NULL);pthread_join(pid_driver, NULL);pthread_join(pid_conductor, NULL);return 0;
}
本文发布于:2024-02-03 04:19:34,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170690517448606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |