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();
锁持有线程释放锁另外获取到锁的线程继续往下执行