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

如何在两个C++11线程中实现同步?解决Factory类线程运行异常

Troubleshooting Your Factory Worker Thread Issues

Hey there! Let’s break down the most likely issues causing your worker threads to behave unexpectedly, and walk through fixes for each:

1. Data Race on the Shared work Variable

The biggest red flag here is your shared work variable being incremented by both threads without any synchronization. When two threads modify the same memory location at the same time, you get data races—this leads to incorrect values, random crashes, or other inconsistent behavior.

Fix:

Use either an atomic variable (for simple increments) or a mutex to guard access to work:

  • Atomic Variable (simplest for this case):
    // Declare work as an atomic type instead of a plain int
    std::atomic<int> work = 0;
    
    // In worker threads, increment normally—atomic handles synchronization
    work++;
    
  • Mutex (for more complex shared operations):
    std::mutex work_mutex;
    int work = 0;
    
    // In worker threads:
    {
        // Lock guard automatically releases the mutex when it goes out of scope
        std::lock_guard<std::mutex> lock(work_mutex);
        work++;
    }
    

2. Broken Synchronization Between Manager and Workers

Your manager needs to wait for both workers to report their daily workHours before calculating the total. If you’re not properly syncing this, you might be aggregating partial data, missing reports, or processing the same day multiple times.

Fix:

Use a condition variable paired with a counter to track when both reports are in:

// Inside Factory class
std::mutex report_mutex;
std::condition_variable report_cv;
int daily_report_count = 0;
std::array<int, 2> daily_work_hours; // Index 0 for worker 0, 1 for worker 1

// Worker thread report logic:
void send_report_to_manager(int thread_id, int current_work, int current_work_hours) {
    std::lock_guard<std::mutex> lock(report_mutex);
    daily_work_hours[thread_id] = current_work_hours;
    daily_report_count++;
    report_cv.notify_one(); // Tell manager a report is ready
}

// Manager's daily aggregation loop:
for (int day = 0; day < 365; day++) {
    std::unique_lock<std::mutex> lock(report_mutex);
    // Wait until both workers have reported
    report_cv.wait(lock, [this](){ return daily_report_count == 2; });

    // Calculate and report total hours to boss
    int total_work_hours = daily_work_hours[0] + daily_work_hours[1];
    report_to_boss(total_work_hours);

    // Reset counter for the next day
    daily_report_count = 0;
}

3. Unhandled Thread Lifetimes or Exceptions

If your manager exits before the worker threads finish, or a worker throws an uncaught exception, you’ll get crashes or incomplete execution.

Fix:

  • Wait for threads to finish: Always call join() on your worker threads in the manager to ensure they complete their work before the program exits:
    // In manager function, after creating threads:
    std::thread worker1(&Factory::worker_loop, this, 0);
    std::thread worker2(&Factory::worker_loop, this, 1);
    
    // Run manager's logic (like waiting for reports)...
    
    // Wait for workers to finish their year-long loop
    worker1.join();
    worker2.join();
    
  • Catch exceptions in workers: Wrap the worker’s loop in a try-catch block to handle errors gracefully instead of letting the thread terminate abruptly:
    void worker_loop(int thread_id) {
        try {
            for (int day = 0; day < 365; day++) {
                // Do daily work: increment workHours and shared work
                workHours++;
                // ... (sync shared work as fixed above)
                send_report_to_manager(thread_id, work, workHours);
            }
        } catch (const std::exception& e) {
            std::cerr << "Worker thread " << thread_id << " failed: " << e.what() << std::endl;
            // Optionally notify manager of the failure
        }
    }
    

4. Misaligned Report Tracking

If your manager isn’t correctly associating each report with the right worker, you might be overwriting workHours values or aggregating the wrong data.

Fix:

Ensure every report from a worker includes its unique thread ID, and the manager uses that ID to store the workHours in the correct position of an array or map (like the daily_work_hours array in the synchronization fix above).


Start with checking for data races first—they’re the most frequent cause of weird multi-threaded behavior. Then verify your manager-worker synchronization to make sure you’re collecting both daily reports before aggregating. Don’t forget to handle thread lifetimes and exceptions to prevent crashes!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:17:47