Baosong Wu - Architect@SR-Intelligence
2020-08
void foo()
{
this_thread::sleep_for(chrono::seconds(1));
}
int main()
{
thread t1(foo);
thread t2([]() {
foo();
});
}{
std::thread t(funcToRun); // t is joinable
... // assume t remians joinable
} // std::terminate is calledvoid foo()
{
this_thread::sleep_for(chrono::seconds(1));
}
int main()
{
thread t1(foo);
thread t2([]() {
foo();
});
t1.join();
t2.join();
}class ThreadRAII
{
public:
enum class DtorAction
{
Join,
Detach
};
ThreadRAII(thread &&t, DtorAction action) : action(action), t(move(t)) {}
~ThreadRAII()
{
if (t.joinable())
{
if (action == DtorAction::Join)
{
t.join();
}
else
{
t.detach();
}
}
}
thread &get()
{
return t;
}
private:
DtorAction action;
thread t;
};dataProducer
...
produce data
...
dataProcessor
...
Block until the data is ready.
...
dataProducer
...
produce data
flag = true;
...
dataProcessor
...
while (!flag)
;
...
atomic<bool> flag(false);
dataProducer
...
produce data
condVar.notify_one();
...
dataProcessor
...
unique_lock<mutex> lock(aMutex);
condVar.wait(lock);
...
mutex aMutex;
condition_variable condVar;
dataProducer
...
produce data
{
unique_lock<mutex> lock(aMutex);
flag = true;
}
condVar.notify_one();
...
dataProcessor
...
{
unique_lock<mutex> lock(aMutex);
condVar.wait(lock, [] { return flag; });
}
...
mutex aMutex;
condition_variable condVar;
bool flag = false;
promise<void> p;
thread t([&p] {
p.get_future().wait(); // start t and suspend it
funcToRun(); }
);
... // t is waiting for p to be set
p.set_value(); // t may now continue
...
t.join();dataProducer
...
produce data
p.set_value();
...
dataProcessor
...
p.get_future().wait();
...
promise<void> p;
dataProducer
...
scope_guard(p.set_exception());
produce data
p.set_value();
scope_guard.Dismiss();
...
dataProcessor
...
try {
p.get_future().get();
}
catch(...) {
...
}
...
promise<void> p;