头文件:#include<semaphore.h>
定义了结构体sem_t;
相关函数:
(1) sem_init (sem_t *sem, int pshared, unsigned int value);
这个函数的作用是对sem_t指定信号量进行初始化。第一个参数是结构体sem_t,;第二个参数是设置它的共享选,如果该参数的值为0,表示不能共享信号量,反之可以共享;第三个参数指定信号两百的初始值。
(2) sem_wait(sem_t * sem);
sem_wait函数也是一个原子操作,它的作用是从信号量的值减去一个“1”,但它永远会先等待该信号量为一个非零值才开始做减法。当信号量的值为0时,则需要等待,直到信号量的值不为1。可以理解为等待资源。如果有资源就给,没有资源就等待。
(3) sem_post(sem_t * sem);
sem_post函数的作用是给信号量的值加上一个“1”。可以理解为是在释放资源。
例子:可以认为这个例子是一个线程同步的过程。
https://leetcode-cn.com/problems/print-in-order
我们提供了一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。
一个将会调用 first() 方法
一个将会调用 second() 方法
还有一个将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
示例 1:
输入: [1,2,3]
输出: "firstsecondthird"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。
正确的输出是 "firstsecondthird"。
示例 2:
输入: [1,3,2]
输出: "firstsecondthird"
解释:
输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。
正确的输出是 "firstsecondthird"。
代码:
#include <semaphore.h>
class Foo {
public:
sem_t f;
sem_t s;
Foo() {
sem_init(&f,0,0);
sem_init(&s,0,0);
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
sem_post(&f);
}
void second(function<void()> printSecond) {
sem_wait(&f);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
sem_post(&s);
}
void third(function<void()> printThird) {
sem_wait(&s);
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
};