C++线程的创建

1.用一个初始函数创建一个线程

#include <iostream>
#include<thread>

using namespace std;

void PinrtFun()
{
    cout << " 子线程运行" << endl;
}

int main()
{
    std::thread t1(PinrtFun);
    t1.join();
    std::cout << "主线程运行
";
}
View Code

2.用类对象创建一个线程

#include <iostream>
#include<thread>

using namespace std;

class  SubThread
{
public:
    SubThread(int &temp) :m_int(temp) {}

    void operator()()
    {
        cout << "1:" << m_int << endl;
        cout << "2:" << m_int << endl;
        cout << "3:" << m_int << endl;
        cout << "4:" << m_int << endl;
        cout << "5:" << m_int << endl;
        cout << "6:" << m_int << endl;
    }

private:
    int m_int;
};

int main()
{
    int temp = 10;
    SubThread subT(temp);
    std::thread t1(subT);
    t1.join();
    std::cout << "主线程运行
";
}
View Code

3.用lambda表达式创建一个线程

#include <iostream>
#include<thread>

using namespace std;

int main()
{
    auto mylamthread = [] {
        cout << "子线程运行" << endl;
    };

    std::thread t1(mylamthread);
    t1.join();
    std::cout << "主线程运行
";
}
View Code

注意:

1.join()和detach()的区别:

  join():主线程会等待子线程运行完才往下运行。

  detach():子线程和主线程都独立运行,相互不影响。当主线程运行完了,而子线程还没运行完时,此时程序会报错。

2.joinable(),这个函数用来判断是否还可以使用join()和detach(),如果已经使用了join()或者detach(),则不能再使用detach()或者join()函数了,会返回一个布尔true,反之,返回一个false。

111
原文地址:https://www.cnblogs.com/zwj-199306231519/p/13526912.html