线程this_thread的全局函数,call_once函数

1, 线程this_thread的全局函数

#include <iostream>
#include <thread>                // 线程类头文件。
using namespace std;

// 普通函数。
void func(int bh, const string& str) {
    cout << "子线程:" << this_thread::get_id() << endl;

    for (int ii = 1; ii <= 1; ii++)
    {
        cout << "第" << ii << "次表白:亲爱的" << bh << "号," << str << endl;
        this_thread::sleep_for(chrono::seconds(1));    // 休眠1秒。
    }
}

int main()
{
    // 用普通函数创建线程。
    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函数

#include <iostream>
#include <thread>        // 线程类头文件。
#include <mutex>        // std::once_flag和std::call_once()函数需要包含这个头文件。
using namespace std;

/*
头文件:#include <mutex>
template< class callable, class... Args >
void call_once( std::once_flag& flag, Function&& fx, Args&&... args );
第一个参数是std::once_flag,用于标记函数fx是否已经被执行过。
第二个参数是需要执行的函数fx。
第三个可变参数是传递给函数fx的参数。
 */

once_flag onceflag;       // once_flag全局变量。本质是取值为0和1的锁。
// 在线程中,打算只调用一次的函数。
void once_func(const int bh, const string& str)  {
    cout << "once_func() bh= " << bh << ", str=" << str << endl;
}

// 普通函数。
void func(int bh, const string& str) {
    call_once(onceflag,once_func,0, "各位观众,我要开始表白了。");

    for (int ii = 1; ii <= 3; ii++)
    {
        cout << "第" << ii << "次表白:亲爱的" << bh << "号," << str << endl;
        this_thread::sleep_for(chrono::seconds(1));    // 休眠1秒。
    }
}

int main()
{
    // 用普通函数创建线程。
    thread t1(func, 3, "我是一只傻傻鸟。");
    thread t2(func, 8, "我有一只小小鸟。");

    t1.join();         // 回收线程t1的资源。
    t2.join();         // 回收线程t2的资源。
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容