今天爱奇艺最后一道多线程怎么写呢?
原程序是吧 main 函数也给出来了,但是如果不修改 main 函数怎么弄呢?我先拿我的代码抛砖引玉吧,bug 是有一定的几率会死锁
本来是可以用信号量的,但是遗憾的是 C++ 11 没有信号量,而我对 Linux C 又不熟悉,所以用的条件变量。
发生死锁的时候屏幕没有任何输出,所以我也不知道到底是那里出了问题
#include <semaphore.h>
#include <time.h>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
using namespace std;
class Foo {
atomic_bool flag { false };
mutex mu0;
mutex mu1;
mutex mu2;
unique_lock<mutex> pt1 { mu0 };
unique_lock<mutex> pt2 { mu1 };
unique_lock<mutex> pt3 { mu2 };
condition_variable fir;
condition_variable sec;
condition_variable th;
public:
Foo() { }
void first() {
std::cout << "first";
sec.notify_one();
}
void second() {
sec.wait(pt2);
std::cout << "second";
th.notify_one();
}
void third() {
th.wait(pt3);
std::cout << "third";
}
};
int main(int argc, char** argv) {
int array[3] = { 1, 3, 2 };
::srand((unsigned)time(NULL));
std::random_shuffle(array, array + 3);
std::thread th1, th2, th3;
std::unique_ptr<Foo> foo(new Foo());
for(int i: array) {
switch(i) {
case 1: th1 = std::thread(&Foo::first, foo.get()); break;
case 2: th2 = std::thread(&Foo::second, foo.get()); break;
case 3: th3 = std::thread(&Foo::third, foo.get()); break;
default: break;
}
}
th1.join();
th2.join();
th3.join();
std::cout << std::endl;
return 0;
} #爱奇艺##笔经#
小鹏汽车工作强度 25人发布