![]() |
#2
rjsp2016-04-18 22:34
|

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <chrono>
std::mutex mt;
std::condition_variable cv;
bool _isReady = 0;
void func()
{
std::unique_lock<std::mutex> lck(mt);
std::cout << "func get the lock" << std::endl;
while(!_isReady)
{
cv.wait(lck);
}
std::cout << "func lock status : " << lck.owns_lock() << std::endl;
// lck.unlock();
_isReady = !_isReady;
cv.notify_all();
// std::this_thread::yield();
// lck.lock();
while(!_isReady)
{
cv.wait(lck);
}
std::cout << "func get the lock the lock status : " << lck.owns_lock() << std::endl;
}
int main()
{
std::unique_lock<std::mutex> lck(mt);
std::cout << "main get the lock" << std::endl;
std::thread t1(func);
_isReady = !_isReady;
lck.unlock();
cv.notify_all();
// std::this_thread::yield();
// lck.lock();
while(_isReady)
{
cv.wait(lck);
}
_isReady = !_isReady;
lck.unlock();
std::this_thread::yield();
t1.join();
return 0;
}
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <chrono>
std::mutex mt;
std::condition_variable cv;
bool _isReady = 0;
void func()
{
std::unique_lock<std::mutex> lck(mt);
std::cout << "func get the lock" << std::endl;
while(!_isReady)
{
cv.wait(lck);
}
std::cout << "func lock status : " << lck.owns_lock() << std::endl;
// lck.unlock();
_isReady = !_isReady;
cv.notify_all();
// std::this_thread::yield();
// lck.lock();
while(!_isReady)
{
cv.wait(lck);
}
std::cout << "func get the lock the lock status : " << lck.owns_lock() << std::endl;
}
int main()
{
std::unique_lock<std::mutex> lck(mt);
std::cout << "main get the lock" << std::endl;
std::thread t1(func);
_isReady = !_isReady;
lck.unlock();
cv.notify_all();
// std::this_thread::yield();
// lck.lock();
while(_isReady)
{
cv.wait(lck);
}
_isReady = !_isReady;
lck.unlock();
std::this_thread::yield();
t1.join();
return 0;
}
编译条件 g++(4.8.4) -std=c++11 -pthread ubuntu 14
我想完成一个功能就是通过对于isReady的改变来控制两个线程的进行,处理不好的就是不能完美的挂起两个进程
我发现的是 如果不解开互斥量 就不能 通过notify_all()激活另一个线程 但是如果解开了 用condition_variable的时候就要再加上,
但是搞不懂为啥再回到main里的时候 回不去了= = 感觉是因为两个线程都是挂起了,所以程序是假死了,但是不知道为什么在func()里面的notify_all()不能唤醒main里的线程
然后就是用yield()的话就会直接结束了程序,所以也是不行_(:-_|)|_