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

实测 std::thread 三类入口与 std::ref、mutex/atomic/thread_local、condvar/future 及 POSIX pthread

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-multithreading.cpp
explore-cpp-multithreading.cpp162 行
#include <atomic>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <pthread.h>
#include <string>
#include <thread>
#include <vector>

static std::atomic<int> g_fn_ptr_ticks{0};
static void fn_ptr_worker(int count) {
    for (int i = 0; i < count; ++i) {
        g_fn_ptr_ticks.fetch_add(1, std::memory_order_relaxed);
    }
}

struct FunctorWorker {
    std::atomic<int>* target;
    void operator()(int count) const {
        for (int i = 0; i < count; ++i) {
            target->fetch_add(1, std::memory_order_relaxed);
        }
    }
};

static void increment_by_ref(int& value, int delta) {
    value += delta;
}

thread_local int tls_value = 7;

struct PthreadTask {
    int delta;
    int* shared_sum;
    pthread_mutex_t* mtx;
};

static void* posix_worker(void* arg) {
    auto* task = static_cast<PthreadTask*>(arg);
    pthread_mutex_lock(task->mtx);
    *(task->shared_sum) += task->delta;
    pthread_mutex_unlock(task->mtx);
    return nullptr;
}

int main() {
    // 1. std::thread with function pointer, functor, lambda, and std::ref
    std::atomic<int> functor_ticks{0};
    std::atomic<int> lambda_ticks{0};
    int ref_counter = 10;

    std::thread t1(fn_ptr_worker, 3);
    std::thread t2(FunctorWorker{&functor_ticks}, 4);
    std::thread t3([&lambda_ticks](int n) {
        for (int i = 0; i < n; ++i) lambda_ticks.fetch_add(1, std::memory_order_relaxed);
    }, 5);
    std::thread t4(increment_by_ref, std::ref(ref_counter), 15);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    std::string act1 = std::to_string(g_fn_ptr_ticks.load()) + "," +
                       std::to_string(functor_ticks.load()) + "," +
                       std::to_string(lambda_ticks.load()) + "," +
                       std::to_string(ref_counter);
    const std::string exp1 = "3,4,5,25";
    bool ok1 = (act1 == exp1);

    // 2. std::mutex + lock_guard, std::atomic, and thread_local isolation
    std::mutex mtx;
    int guarded_sum = 0;
    std::atomic<int> atomic_sum{0};
    std::vector<int> observed_tls(4, 0);
    std::vector<std::thread> workers;
    for (int id = 0; id < 4; ++id) {
        workers.emplace_back([&, id]() {
            tls_value = 100 + id;
            observed_tls[id] = tls_value;
            for (int k = 0; k < 500; ++k) {
                {
                    std::lock_guard<std::mutex> lk(mtx);
                    ++guarded_sum;
                }
                atomic_sum.fetch_add(1, std::memory_order_relaxed);
            }
        });
    }
    for (auto& w : workers) w.join();
    bool tls_isolated = (tls_value == 7) && (observed_tls[0] == 100) && (observed_tls[3] == 103);
    std::string act2 = "mtx=" + std::to_string(guarded_sum) +
                       ",atom=" + std::to_string(atomic_sum.load()) +
                       ",tls=" + (tls_isolated ? "ok" : "bad");
    const std::string exp2 = "mtx=2000,atom=2000,tls=ok";
    bool ok2 = (act2 == exp2);

    // 3. std::condition_variable + unique_lock & std::promise / std::future
    std::mutex cv_mtx;
    std::condition_variable cv;
    bool ready = false;
    int cv_payload = 0;

    std::thread consumer([&]() {
        std::unique_lock<std::mutex> ul(cv_mtx);
        cv.wait(ul, [&]() { return ready; });
        cv_payload *= 2;
    });
    {
        std::lock_guard<std::mutex> lk(cv_mtx);
        cv_payload = 21;
        ready = true;
    }
    cv.notify_one();
    consumer.join();

    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread producer([&prom]() { prom.set_value(10); });
    int fut_val = fut.get();
    producer.join();

    std::string act3 = "cv=" + std::to_string(cv_payload) + ",fut=" + std::to_string(fut_val);
    const std::string exp3 = "cv=42,fut=10";
    bool ok3 = (act3 == exp3);

    // 4. POSIX pthread_create + pthread_join + pthread_mutex_t
    pthread_mutex_t pmtx = PTHREAD_MUTEX_INITIALIZER;
    int posix_sum = 0;
    pthread_t pthreads[3];
    PthreadTask tasks[3] = {
        {10, &posix_sum, &pmtx},
        {20, &posix_sum, &pmtx},
        {30, &posix_sum, &pmtx},
    };
    for (int i = 0; i < 3; ++i) {
        pthread_create(&pthreads[i], nullptr, posix_worker, &tasks[i]);
    }
    for (int i = 0; i < 3; ++i) {
        pthread_join(pthreads[i], nullptr);
    }
    pthread_mutex_destroy(&pmtx);
    bool ok4 = (posix_sum == 60);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"thread_three_callables_and_ref\", \"expected\": \"" << exp1
              << "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"mutex_atomic_and_thread_local\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"condvar_and_promise_future\", \"expected\": \"" << exp3
              << "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"posix_pthread_mutex_sum\", \"expected\": 60, \"actual\": "
              << posix_sum << ", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    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-multithreading-lab/explore-cpp-multithreading.cpp

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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