You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++多线程仅首个线程可正常join,其余线程报错问题排查

线程完成状态检测与线程池join错误问题

测试代码异常问题

测试代码在n=1时可正常执行,但当n>1时多数情况下触发系统错误。需要找到比传递布尔指针更优雅的非阻塞线程完成状态检测方案,joinable()方法会阻塞主线程,不符合需求。

补充约束:

  • 线程的join顺序无关紧要
  • 主线程不能被阻塞,因此不能提前调用join
  • 已尝试使用atomic<bool>,但未解决问题

测试代码如下:

#include <iostream>
#include <thread>
#include <atomic>
#include <array>

void my_function(bool* is_thread_done) {
    std::cout << "Thread started" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Thread finished" << std::endl;
    *is_thread_done = true;
}

int main() {   
    const int n = 1;
    std::array<std::thread, n> arr;
    std::array<bool, n> is_thread_done;
    for (int i = 0; i < n; i++) {
        is_thread_done[i] = false;
        arr[i] = std::thread(my_function, &is_thread_done[i]);
    }
    
    int all_done = 0;
    while (all_done < n) {
        for (int i = 0; i < n; i++) {
            if (is_thread_done[i]) {
                arr[i].join();
                all_done++;
            }
        }
    }

    return 0;
}

线程池join错误问题

正在实现一个线程池:n个线程执行k次任务(k>n),要求线程完成后立即调度新任务,而非等待所有n个线程完成。但代码运行时出现thread::join failed: Invalid argument Abort trap: 6错误,已调整availability[i]的赋值位置以避免竞态条件,但问题仍存在。

线程池代码如下:

template<typename Func, typename... Args>
void ThreadPool::thread_pool_executor(Func func, Args... args) {
    while (running) {
        while (free_indecies.size() > 0 && running) {
            int i = free_indecies.front();
            pool[i] = std::make_unique<std::thread>(
                &ThreadPool::worker<Func, Args...>, this,
                &avalability[i], func, args...);
            free_indecies.pop();
            avalability[i] = false;
            current_iter++;
            if (current_iter == total_iter) running = false;
        }
        for (int i = 0; i < max_threads; i++) {
            if (avalability[i]) {
                pool[i]->join();
                free_indecies.push(i);
            }
        }
    }
    for (int i = 0; i < max_threads; i++) {
        if (pool[i]->joinable()) {
            pool[i]->join();
        }
    }
    reset();
}

template<typename Func, typename... Args>
void ThreadPool::worker(std::atomic<bool>* complete, Func func, Args... args) {
    std::invoke(func, args...);
    *complete = true;
}

内容的提问来源于stack exchange,提问作者zjschrage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:45:25