赞
踩
#include <iostream> #include <thread> #include <vector> #include <atomic> #include <tbb/task_arena.h> using namespace std; constexpr int THREAD_NUM = 10; atomic<int> a(0); void test(int b) { int expected = a; // 使用了CAS while (!atomic_compare_exchange_weak(&a, &expected, a + b)); } int main() { vector<thread> threads; threads.reserve(static_cast<size_t>(THREAD_NUM)); // 假如有任务数为 100 个(编号为0,1,...,99), 平分到10个线程上去,每个线程执行10个任务 int TASK_NUM = 100; int AVG_NUM = TASK_NUM / THREAD_NUM; for (int i = 0; i < THREAD_NUM - 1; ++i) { threads.emplace_back([i, AVG_NUM](){ for (int j = i * AVG_NUM; j < (i + 1) * AVG_NUM; j++) { test(j + 1); } }); } threads.emplace_back([&](){ for (int j = (THREAD_NUM - 1) * AVG_NUM; j < TASK_NUM; j++) { test(j + 1); } }); for (auto &t : threads) { t.join(); } cout << "a = " << a << endl; // 计算结果为5050,计算正确 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。