我是多线程编程的新手,我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)