// atomic_flag as a spinning lock
#include <iostream> // std::cout
#include <atomic> // std::atomic_flag
#include <thread> // std::thread
#include <vector> // std::vector
#include <sstream> // std::stringstream
std::atomic_flag lock_stream = ATOMIC_FLAG_INIT;
std::stringstream stream;
void append_number(int x) {
while (lock_stream.test_and_set()) {}
stream << "thread #" << x << '\n';
lock_stream.clear();
}
int main()
{
std::vector<std::thread> threads;
for (int i = 1; i <= 10; ++i) threads.push_back(std::thread(append_number, i));
for (auto& th : threads) th.join();
std::cout << stream.str();
return 0;
}
上面是使用atomic_flag
實現的一個簡單的自旋鎖,這是www.cplusplus.com
給出的示例程序。
一直對std::amotic_flag
的成員函數test_and_set()
理解不到位。可以換一種方式思考。
std::atomic_flag lock_stream = ATOMIC_FLAG_INIT;
被初始化後即爲false
調用test_and_set()
時,如果lock_stream
是false
,將其設置爲true
, 然後該函數返回false
;如果lock_stream
爲true
, 不進行設置(因爲已經爲true了), 返回true
。
void append_number(int x)
函數中,當lock_stream
獲得鎖時(即lock_stream之前爲false,被設置爲true),lock_stream.test_and_set()
返回false,退出while()循環,執行之後的代碼。其他線程由於lock_stream.test_and_set()
未獲得鎖,返回true
,之後循環嘗試直到獲取到鎖退出循環。