C++11 atomic_flag總結

// 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_streamfalse,將其設置爲true, 然後該函數返回false;如果lock_streamtrue, 不進行設置(因爲已經爲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,之後循環嘗試直到獲取到鎖退出循環。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章