测试代码-
#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;
}
输出结果:
thread #1::get lock
thread #1::release lock
thread #9::get lock
thread #9::release lock
thread #4::get lock
thread #4::release lock
thread #8::get lock
thread #8::release lock
thread #7::get lock
thread #7::release lock
thread #10::get lock
thread #10::release lock
thread #2::get lock
thread #2::release lock
thread #6::get lock
thread #6::release lock
thread #3::get lock
thread #3::release lock
thread #5::get lock
thread #5::release lock
请按任意键继续. . .