1, 線程this_thread的全局函數(shù)
#include <iostream>
#include <thread> // 線程類頭文件。
using namespace std;
// 普通函數(shù)隧甚。
void func(int bh, const string& str) {
cout << "子線程:" << this_thread::get_id() << endl;
for (int ii = 1; ii <= 1; ii++)
{
cout << "第" << ii << "次表白:親愛的" << bh << "號(hào)蓖乘," << str << endl;
this_thread::sleep_for(chrono::seconds(1)); // 休眠1秒查吊。
}
}
int main()
{
// 用普通函數(shù)創(chuàng)建線程仙逻。
thread t1(func, 3, "我是一只傻傻鳥服鹅。");
thread t2(func, 8, "我有一只小小鳥涵但。");
cout << "主線程:" << this_thread::get_id() << endl;
cout << "線程t1:" << t1.get_id() << endl;
cout << "線程t2:" << t2.get_id() << endl;
t1.join(); // 回收線程t1的資源杈绸。
t2.join(); // 回收線程t2的資源。
}
2, call_once函數(shù)
#include <iostream>
#include <thread> // 線程類頭文件矮瘟。
#include <mutex> // std::once_flag和std::call_once()函數(shù)需要包含這個(gè)頭文件瞳脓。
using namespace std;
/*
頭文件:#include <mutex>
template< class callable, class... Args >
void call_once( std::once_flag& flag, Function&& fx, Args&&... args );
第一個(gè)參數(shù)是std::once_flag,用于標(biāo)記函數(shù)fx是否已經(jīng)被執(zhí)行過澈侠。
第二個(gè)參數(shù)是需要執(zhí)行的函數(shù)fx劫侧。
第三個(gè)可變參數(shù)是傳遞給函數(shù)fx的參數(shù)。
*/
once_flag onceflag; // once_flag全局變量哨啃。本質(zhì)是取值為0和1的鎖烧栋。
// 在線程中,打算只調(diào)用一次的函數(shù)拳球。
void once_func(const int bh, const string& str) {
cout << "once_func() bh= " << bh << ", str=" << str << endl;
}
// 普通函數(shù)审姓。
void func(int bh, const string& str) {
call_once(onceflag,once_func,0, "各位觀眾,我要開始表白了祝峻。");
for (int ii = 1; ii <= 3; ii++)
{
cout << "第" << ii << "次表白:親愛的" << bh << "號(hào)魔吐," << str << endl;
this_thread::sleep_for(chrono::seconds(1)); // 休眠1秒扎筒。
}
}
int main()
{
// 用普通函數(shù)創(chuàng)建線程。
thread t1(func, 3, "我是一只傻傻鳥酬姆。");
thread t2(func, 8, "我有一只小小鳥嗜桌。");
t1.join(); // 回收線程t1的資源。
t2.join(); // 回收線程t2的資源轴踱。
}