第一次做多线程的题目,以前学过的操作系统好多知识都忘记了,题解描述的很详细,可以用锁或者信号量来实现。
不同编程语言实现的方法不同,python用到的是threading库,c++中用到的是semaphore.h这个库
#includeclass Foo { protected: sem_t firstJobDone; sem_t secondJobDone; public: Foo() { sem_init(&firstJobDone, 0, 0); sem_init(&secondJobDone, 0, 0); } void first(function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); sem_post(&firstJobDone); } void second(function printSecond) { sem_wait(&firstJobDone); // printSecond() outputs "second". Do not change or remove this line. printSecond(); sem_post(&secondJobDone); } void third(function printThird) { sem_wait(&secondJobDone); // printThird() outputs "third". Do not change or remove this line. printThird(); } };
其中,sem_init(&firstJobDone, 0, 0);这句话中,后面两个0的含义为:



