蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 <condition_variable> 安全停机生产者-消费者、notify_all 广播与 wait_for 超时/唤醒

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-condition-variable.cpp
explore-cpp-libs-condition-variable.cpp183 行
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <iostream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: bounded producer-consumer with clean shutdown flag (no infinite consumer loop)
    std::mutex mtx;
    std::condition_variable cv;
    std::queue<int> product;
    std::vector<int> consumed;
    bool producers_done = false;

    auto producer = [&](int id) {
        for (int i = 0; i < 5; ++i) {
            {
                std::unique_lock<std::mutex> lck(mtx);
                product.push(id * 100 + i);
            }
            cv.notify_one();
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    };

    auto consumer = [&]() {
        while (true) {
            std::unique_lock<std::mutex> lck(mtx);
            cv.wait(lck, [&]() { return !product.empty() || producers_done; });
            if (!product.empty()) {
                int item = product.front();
                product.pop();
                consumed.push_back(item);
            } else if (producers_done) {
                break;
            }
        }
    };

    std::thread p1(producer, 1), p2(producer, 2);
    std::thread c1(consumer), c2(consumer);
    p1.join();
    p2.join();
    {
        std::lock_guard<std::mutex> lck(mtx);
        producers_done = true;
    }
    cv.notify_all();
    c1.join();
    c2.join();

    std::sort(consumed.begin(), consumed.end());
    std::vector<int> exp_items = {100, 101, 102, 103, 104, 200, 201, 202, 203, 204};
    bool ok1 = (consumed == exp_items) && product.empty();
    cases.push_back({
        "cv_producer_consumer_bounded",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: notify_all wakes all 3 waiting threads
    std::mutex bmtx;
    std::condition_variable bcv;
    bool go = false;
    int arrived = 0;
    int woken = 0;
    auto worker = [&]() {
        std::unique_lock<std::mutex> lk(bmtx);
        ++arrived;
        bcv.notify_all();
        bcv.wait(lk, [&]() { return go; });
        ++woken;
    };
    std::thread w1(worker), w2(worker), w3(worker);
    {
        std::unique_lock<std::mutex> lk(bmtx);
        bcv.wait(lk, [&]() { return arrived == 3; });
        go = true;
    }
    bcv.notify_all();
    w1.join();
    w2.join();
    w3.join();
    cases.push_back({
        "cv_notify_all_broadcast",
        std::to_string(3),
        std::to_string(woken),
        woken == 3
    });

    // Case 3: wait_for timeout (false) and signaled wakeup (true)
    std::mutex tmtx;
    std::condition_variable tcv;
    bool flag = false;
    bool timed_out_res = true;
    {
        std::unique_lock<std::mutex> lk(tmtx);
        timed_out_res = tcv.wait_for(lk, std::chrono::milliseconds(10), [&]() { return flag; });
    }
    std::thread notifier([&]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
        {
            std::lock_guard<std::mutex> lk(tmtx);
            flag = true;
        }
        tcv.notify_one();
    });
    bool woken_res = false;
    {
        std::unique_lock<std::mutex> lk(tmtx);
        woken_res = tcv.wait_for(lk, std::chrono::milliseconds(500), [&]() { return flag; });
    }
    notifier.join();
    bool ok3 = (!timed_out_res) && woken_res;
    cases.push_back({
        "cv_wait_for_timeout_and_wakeup",
        lab::jbool(true),
        lab::jbool(ok3),
        ok3
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-condition-variable-lab/explore-cpp-libs-condition-variable.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-condition-variable.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2340.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习