小编dra*_*rve的帖子

我怎样才能正确地增加C++ 11 std :: atomic?

我是多线程编程的新手,我std::atomic在C++ 11中找到了它.

所以,我试图弄清楚原子操作需要多长时间.

我试过这段代码:

using namespace std;
using namespace std::chrono;

constexpr int NUM_THREADS = 8;
constexpr int LIMIT = 100000;

atomic<int> sum = 0;

void foo(int idx) {
    while (true) {
        if (sum.load() >= LIMIT) {
            return;
        }
        sum.fetch_add(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

main:

int main(void) {
    thread threads[NUM_THREADS];

    auto start = high_resolution_clock::now();

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = thread(&foo, i);
    }

    for (int i = 0; i < NUM_THREADS; i++) { …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading atomic c++11 stdatomic

4
推荐指数
1
解决办法
1132
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

multithreading ×1

stdatomic ×1