小编sch*_*dge的帖子

C++ 11 可以在不同线程中通过引用安全地传递和访问 std::atomics

我想知道您是否可以通过引用线程来传递原子,并且 .load 和 .store 操作仍然是线程安全的。例如:

#include <thread>
#include <atomic>
#include <cstdlib>

void addLoop(std::atomic_int& adder)
{
    int i = adder.load();
    std::srand(std::time(0));
    while(i < 200)
    {
        i = adder.load();
        i += (i + (std::rand() % i));
        adder.store(i);
    }
}

void subLoop (std::atomic_int& subber)
{
    int j = subber.load();
    std::srand(std::time(0));
    while(j < 200)
    {
        j = subber.load();
        j -= (j - (std::rand() % j));
        subber.store(j);
    }
}

int main()
{
    std::atomic_int dummyInt(1);
    std::thread add(addLoop, std::ref(dummyInt));
    std::thread sub(subLoop, std::ref(dummyInt));
    add.join();
    sub.join();
    return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading atomic pass-by-reference c++11

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

标签 统计

atomic ×1

c++ ×1

c++11 ×1

multithreading ×1

pass-by-reference ×1