c++11 stl atomic_flag 样例

Author:DriverMonkey

Mail:bookworepeng@Hotmail.com

Phone:13410905075

QQ:196568501


測试环境:Win7 64 bit

编译器:gcc 4.81

測试代码-

/*********************************************************************************
 Copyright (C), 1988-1999, drvivermonkey. Co., Ltd.
 File name: 
 Author: Driver Monkey
 Version: 
 Mail:bookworepeng@hotmail.com
 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;
}


以上代码执行结果:




总结:

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

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

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

转载于:https://www.cnblogs.com/lcchuguo/p/4490609.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值