std::thread 一:创建线程的三种方式

前言:

#include <thread>

thread.join()      // 阻塞
thread.detach()    // 非阻塞
thread.joinable()  // bool,判断线程是否支持join或者detach

 

正文:

创建线程有三种方式,分别是:使用函数来创建线程、使用自定义的类来创建线程、使用lambda函数来创建线程

 

一、使用函数来创建线程

void func1()
{
    cout << "我是不带参数的函数" << endl;
}

void func2(int num) 
{ 
    cout << "我是带参数的函数,参数是:" << num << endl;
}

int main()
{
    cout << "thread begin" << endl;

    thread t1(func1);
    t1.join();

    thread t2(func2, 10);
    t2.join();

    cout << "thread end" << endl;
    
    return 0;
}

 

二、使用自定义的类来创建线程

#include <iostream>
#include <thread>
using namespace std;

class myClass1
{
public:
    // 重写operator方法
    void operator()()
    {
        cout << "我是不带参数的类" << endl;
    }
};

class myClass2
{
public:
    int m_i;
    myClass2(int i) :m_i(i) {};
    void operator()()
    {
        cout << "我是带参数的类,参数是:" << m_i << endl;
    }
};

int main()
{
    cout << "thread begin" << endl;

    myClass1 c1;
    thread t1(c1);
    t1.join();

    myClass2 c2(6);
    thread t2(c2);
    t2.join();

    cout << "thread end" << endl;
    return 0;
}

 

 

三、使用lambda表达式来创建线程

#include <iostream>
#include <thread>
using namespace std;

int main()
{
    cout << "thread begin" << endl;

    auto myLambda1 = [] {
        cout << "卡布达  卡布达 我是不带参数的 lambda" << endl;
    };

    auto myLambda2 = [](int num) {
        cout << "卡布达  卡布达 我是带参数的lambda,参数是:" << num << endl;
    };

    thread t1(myLambda1);
    t1.join();

    thread t2(myLambda2, 666);
    t2.join();

    cout << "thread end" << endl;

    return 0;
}

 

posted @ 2023-06-18 22:52  十一的杂文录  阅读(201)  评论(0编辑  收藏  举报