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 << ‘\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; }
以上代码运行结果:
如果屏蔽掉 //while (lock_stream.test_and_set()) 这一句代码运行结果:
总结:
第一组代码线程内部加锁部分代码整个运行顺序和创建顺序一致。
第二组代码线程内部代码整个穿插运行的,没有先后顺序
对比两组代码运行结果可以看出加锁成功