// c++11 標準庫使用atomic 自旋鎖(只要有鎖阻塞等待的鎖)
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
#include <sstream>
//使用宏賦初值
std::atomic_flag lock_stream = ATOMIC_FLAG_INIT;
std::stringstream stream;
void append_number(int x) {
//test_and_set() 成功設置說明沒有互斥返回false,設置不成功返回false繼續while循環形成自旋鎖
while (lock_stream.test_and_set())
{
std::cout << "test_and_set" << std::endl;
}
stream << "thread #" << x << '\n';
//清除鎖
lock_stream.clear();
}
int main()
{
std::vector<std::thread> threads;
for (int i = 1; i <= 10; ++i) threads.push_back(std::thread(append_number, i));
for (auto& th : threads) th.join();
std::cout << stream.str();
return 0;
}
std::this_thread::yield(); 的使用
//10個線程競爭看哪一個執行打印語句
#include <iostream> // std::cout
#include <atomic> // std::atomic, std::atomic_flag, ATOMIC_FLAG_INIT
#include <thread> // std::thread, std::this_thread::yield
#include <vector> // std::vector
std::atomic<bool> ready(false);
std::atomic_flag winner = ATOMIC_FLAG_INIT;
void count1m(int id) {
while (!ready)
{
//當前線程放棄執行,操作系統調度另一線程繼續執行。
//即當前線程將未使用完的“CPU時間片”讓給其他線程使用,
//等其他線程使用完後再與其他線程一起競爭"CPU"
std::this_thread::yield();
}
for (int i = 0; i < 1000000; ++i) {}
if (!winner.test_and_set())
{
std::cout << "thread #" << id << " 線程成功打印!\n";
}
};
int main()
{
std::vector<std::thread> threads;
std::cout << "10個線程 每個執行1百萬for循環...\n";
for (int i = 1; i <= 10; ++i) threads.push_back(std::thread(count1m, i));
ready = true;
for (auto& th : threads) th.join();
return 0;
}