小编Tyl*_*ler的帖子

C++条件变量为什么需要锁?

在参考文档中std::condition_variable有这个例子:

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
 
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
 
void worker_thread()
{
    // Wait until main() sends data
    std::unique_lock lk(m);
    cv.wait(lk, []{ return ready; });
 
    // after the wait, we own the lock.
    std::cout << "Worker thread is processing data\n";
    data += " after processing";
 
    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completed\n"; …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading condition-variable c++11 c++20

3
推荐指数
1
解决办法
224
查看次数

标签 统计

c++ ×1

c++11 ×1

c++20 ×1

condition-variable ×1

multithreading ×1