Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Foo {
public:
Foo() {
m1.lock();
m2.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
m1.unlock();
}
void second(function<void()> printSecond) {
m1.lock();
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
m2.unlock();
}
void third(function<void()> printThird) {
m2.lock();
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
mutex m1;
mutex m2;
};
#include <semaphore.h>
class Foo {
public:
Foo() {
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 0);
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
sem_post(&s1);
}
void second(function<void()> printSecond) {
sem_wait(&s1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
sem_post(&s2);
}
void third(function<void()> printThird) {
sem_wait(&s2);
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
sem_t s1;
sem_t s2;
};
class Foo {
public:
Foo() {}
void first(function<void()> printFirst) {
unique_lock<mutex> l{m};
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
b1 = true;
cv1.notify_one();
}
void second(function<void()> printSecond) {
unique_lock<mutex> l{m};
cv1.wait(l, [this] { return b1; });
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
b2 = true;
cv2.notify_one();
}
void third(function<void()> printThird) {
unique_lock<mutex> l{m};
cv2.wait(l, [this] { return b2; });
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
mutex m;
condition_variable cv1;
condition_variable cv2;
bool b1 = false;
bool b2 = false;
};