首页 > 解决方案 > 在 C++ 中使用多线程进行重复模拟

问题描述

我想多次模拟一个场景,即repCnt = 100。为了加快进程,我想使用多个线程,它们并行工作并在必须将结果记录到文件中时使用互斥锁。

他们需要通过在 NUM_THREADS = 4 组中工作来从总重复次数中扣除。使用互斥锁的日志记录部分很容易,但我不知道主循环应该是什么样子。

这是一个开始:

NUM_THREADS = 4

void simulate(struct argType arg) {

}


int main() {
    // ... Some code here ... 

    vector<thread> vecOfThreads;

    for (rep = 0; rep < repCnt; rep++) {

        // Here they should work in groups of 4, i.e., rep = 1, 2, 3, 4

        // They need to call the simulate(struct argType) function while they are working

        // Once a thread is done, it should get the next task from the loop, i.e., rep = 5

    } 

    return 0;
}

当我在 C++ 中搜索线程池时,我发现所有的类和方法都太多了。应该有一种更快的方法来完成我想要实现的目标。有人可以用最简单和最短的 C++ 代码帮助我吗?

标签: c++multithreadingthreadpool

解决方案


使用仅标头cxxpool

#include "cxxpool.h"
#include <iostream>
#include <mutex>
#include <thread>

std::mutex cout_mutex;

struct some_arg {
    int i;
};

void simulate(const some_arg arg) {
    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << "Hello from task #" << arg.i << " and thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    cxxpool::thread_pool pool{4};
    for (int i = 0; i < 100; i++) {
        pool.push(simulate, some_arg{i});
    }
}

推荐阅读