std::atomic<int> unique_ids;
void foo() {
int i = unique_ids.fetch_add(1, std::memory_order_relaxed);
std::cout<<i;
}
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
for (int i = 0; i < 9; ++i) {
threads.emplace_back(foo);
}
for (int i = 0; i < 9; ++i) {
threads[i].join();
}
std::cout << std::endl;
return 0;
}
我的目標是使用原子來爲併發程序生成唯一的ID,但我不在乎命令。瞭解C++中的內存順序
對於上面的代碼,我的理解是,foo中的輸出值應該是不同的,儘管它們的順序不能保證。
我測試了上面的代碼百次,所有的結果都是我的預期。我是原子/記憶順序的初學者,誰能幫我澄清我的理解?
在此先感謝。 Aimin
P.S.我想指出這個問題與c++,std::atomic, what is std::memory_order and how to use them不一樣,因爲我的問題是關於memory_order_relaxed的理解,而不是關於原子和內存順序解釋的一般問題。
@πάνταῥεῖ這是關於'memory_order_relaxed'而不是'memory_order'。 – nbro
@πάνταῥεῖ我認爲我的問題是不一樣的[C++,std :: atomic,什麼是std :: memory_order以及如何使用它們](http://stackoverflow.com/questions/9553591/c-stdatomic因爲我的問題具體是關於memory_order_relaxed的理解。謝謝。 –
@πάνταῥεῖ這是關於一個特定的問題,而不是一般的概念。重複關閉不正確。 – 2501