c++11 stl atomic_flag例
2330 ワード
Author:DriverMonkey Mail:[email protected]:1340109005075 QQ:196568501試験環境:Win 7 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"<<'
';
this_thread::sleep_for (chrono::seconds(1));//sleep check for if over thread can get the lock
stream << "thread #" << x<<"::release lock"<< '
';
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();
ロックスレッドリリースロックを保持ロックロックロックロックを取得ロックを取得したスレッドは引き続き実行されます