在主线程中锁定 std::mutex 然后在子线程中解锁是否合法。 这是一个演示snippet,它似乎有效。
#include <iostream>
#include <mutex>
#include <thread>
int main()
{
std::mutex mtx;
mtx.lock();
std::thread([&](){mtx.unlock();}).join();
std::thread([&](){mtx.lock();}).join();
}
这是我最常用的模式之一,让线程相互等待,不需要传递锁。
#include <mutex>
#include <condition_variable>
#include <iostream>
int main()
{
std::mutex mtx;
// despite its name a condition variable is more of an interthread signal
// signalling something has changed that is worth checking
std::condition_variable cv;
bool thread1_finished{ false };
std::thread thread1{ [&]
{
std::cout << "thread 1 doing stuff\n";
std::scoped_lock lock{mtx};
thread1_finished = true;
cv.notify_all();
}};
std::thread thread2{ [&]
{
// wait for thread 1 to finish
{
std::unique_lock lock{mtx};
// this is not a busy wait.
// thread will go to sleep until cv is signalled
// and then it will check the predicate
cv.wait(lock, [&] { return thread1_finished; });
}
std::cout << "thread 2 doing stuff\n";
}};
thread1.join();
thread2.join();
return 1;
}