c++ - 在 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++ 代码帮助我吗?
解决方案
使用仅标头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});
}
}
推荐阅读
- python - 如何从 Qdialog 窗口返回
- python - 无法在 Gcloud 上部署 Django 项目
- java - 从 Scala 访问 HBase 时发生了非法反射访问操作
- javascript - Wordpress 使用 javascript 更改 iframe src
- c# - Hangfire、EF dbContext 和 JSON 参考循环
- android - 在深度打盹模式测试中未收到 FCM 高优先级消息
- javascript - 在 JS/ES6 中获取枚举键的文字字符串
- amazon-web-services - 如何创建一个蟒蛇蛋?并火花提交
- javascript - Javascript 对象变量常量
- mongodb - 如何优化聚合查询以根据不同的键进行分组?