互斥量守护着condition_variable
的内部状态。在condition_variable
上调用wait
会导致互斥锁被解锁。所以在等待时,线程不拥有互斥量。
当wait
完成时,在调用wait
返回之前,互斥量再次(原子地)获取。
线程没有在互斥体上竞争,它们正在竞争条件本身。
如果您愿意,只要您从等待中返回,您就可以自由解锁。例如,如果您希望允许多个线程在某种情况下进行同步,则您将如何执行此操作。您也可以使用此功能来实现信号量。
例如:
此代码处理的事情在10注批次是notify_all()
去后的unlock()
:
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <vector>
void emit(std::string const& s)
{
static std::mutex m;
auto lock = std::unique_lock<std::mutex>(m);
std::cout << s << std::endl;
}
std::mutex m;
std::condition_variable cv;
int running_count = 0;
void do_something(int i)
{
using namespace std::literals;
auto lock = std::unique_lock<std::mutex>(m);
// mutex is now locked
cv.wait(lock, // until the cv is notified, the mutex is unlocked
[]
{
// mutex has been locked here
return running_count < 10;
// if this returns false, mutex will be unlocked again, but code waits inside wait() for a notify()
});
// mutex is locked here
++running_count;
lock.unlock();
// we are doing work after unlocking the mutex so others can also
// work when notified
emit("running " + std::to_string(i));
std::this_thread::sleep_for(500ms);
// manipulating the condition, we must lock
lock.lock();
--running_count;
lock.unlock();
// notify once we have unlocked - this is important to avoid a pessimisation.
cv.notify_all();
}
int main()
{
std::vector<std::thread> ts;
for (int i = 0 ; i < 200 ; ++i)
{
ts.emplace_back([i] { do_something(i); });
}
for (auto& t : ts) {
if (t.joinable()) t.join();
}
}
让我引导您有很大的参考/例如站点:http:/ /en.cppreference.com/w/cpp/thread/condition_variable – NathanOliver
它不能解决我的问题。抱歉。 –