c++11 stl atomic_flag 样例

Author:DriverMonkey

Mail:[email protected]

Phone:13410905075

QQ:196568501


測试环境:Win7 64 bit

编译器:gcc 4.81

測试代码-

/*********************************************************************************
 Copyright (C), 1988-1999, drvivermonkey. Co., Ltd.
 File name: 
 Author: Driver Monkey
 Version: 
 Mail:[email protected]
 Date: 2014.04.02
 Description:  Test std lib automic_flag
 *********************************************************************************/
#include <iostream>       // std::cout
#include <atomic>         // std::atomic_flag
#include <thread>         // std::thread
#include <vector>         // std::vector
#include <sstream>       // std::stringstream

using namespace std;

atomic_flag lock_stream = ATOMIC_FLAG_INIT;
stringstream stream;

void append_number(int x)
{
	while (lock_stream.test_and_set())
	{
		;
	}
	
 	stream << "thread #" << x <<"::get lock"<<'\n';
 	this_thread::sleep_for (chrono::seconds(1));//sleep check for if over thread can get the lock
 	stream << "thread #" << x<<"::release lock"<< '\n';
 	
 	lock_stream.clear();
}

int main ()
{
	std::vector<std::thread> threads;
	
	for (int i=1; i<=10; ++i)
	{
		threads.push_back(thread(append_number,i));//create thread
	}
	
	for (auto& th : threads) 
	{
		th.join();// wait thread return
	}

	cout << stream.str();
	
	return 0;
}


以上代码执行结果:

c++11 stl atomic_flag 样例_第1张图片



总结:

线程获取锁后 sleep 进行释放当前执行CPU资源, 通过信息打印能够看出,其它线程执行到

while (lock_stream.test_and_set())
获取锁代码就没再往下运行,直到

lock_stream.clear();
锁持有线程释放锁另外获取到锁的线程继续往下运行

你可能感兴趣的:(atomic)