【发布时间】:2018-11-13 14:50:15
【问题描述】:
来自std::condition_variable::notify_one的示例代码。
我的问题是:
通知线程是否可以在通知线程的wait函数锁定之前锁定,因为notify操作不会阻塞当前线程?
代码:(我把原来的cmets删掉了)
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cout << "Waiting... \n";
cv.wait(lk, []{return i == 1;}); //Waiting
std::cout << "...finished waiting. i == 1\n";
done = true;
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Notifying falsely...\n";
cv.notify_one(); //Notifying
std::unique_lock<std::mutex> lk(cv_m);//Is it possible for this line to execute
//before cv.waits() in waits() tries to lock ?
i = 1;
while (!done)
{
std::cout << "Notifying true change...\n";
lk.unlock();
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
lk.lock();
}
}
int main()
{
std::thread t1(waits), t2(signals);
t1.join();
t2.join();
}
【问题讨论】:
-
是的,可以通过在等待线程之前通知线程来锁定。但它是如何使代码不安全的呢?
-
@bartop 是的,你是对的.. 即使这样也不会使代码不安全。顺便说一句,是否有任何保证执行顺序的规则?还是只是未定义?
标签: c++ multithreading operator-precedence