C++11多线程创建的三种方法

  在每个C++应用程序中,都有一个主线程(main函数)。在C++11标准中,创建线程可以通过类std::thread来创建。该类需要包含头文件:

初始化std::thread类对象,有三种参数传递方式:

  函数指针
  类对象
  lambda表达式

例如,可以这样创建线程对象:
在这里插入图片描述
线程对象创建后,就可以并行地执行传递的回调函数。
如果在退出前,想等待所有线程结束再退出,可以使用join()函数。
线程在运行过程中,如果区分线程呢?

  每个线程都有自己的线程ID,通过std::thread创建的线程可以使用std::thread::get_id()来获取线程ID。

比如获取当前线程ID:

  std::this_thread::get_id()

如果std::thread没有关联任何线程对象,那么get_id()会返回一个std::thread的默认构造函数对象。

1. 使用函数指针创建线程

在这里插入图片描述
运行结果:
在这里插入图片描述
附上例代码:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

void thread_function()
{
    
    
    for(int i=0;i<10000;i++)
        cout<<"thread function Executing"<<endl;
}

int main()
{
    
    
    thread threadObj(thread_function);
    for(int i=0;i<10000;i++)
        cout<<"Display From MainThread"<<endl;
    threadObj.join();
    cout<<"Exit of Main function"<<endl;
    return 0;
}

2. 使用类对象创建线程

在这里插入图片描述
运行结果:
在这里插入图片描述
附上例代码:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

class DisplayThread
{
    
    
public:
	void operator()()
	{
    
    
    for(int i=0;i<10000;i++)
        cout<<"thread function Executing"<<endl;
	}
};

int main()
{
    
    
    thread threadObj((DisplayThread()));
    for(int i=0;i<10000;i++)
        cout<<"Display From MainThread"<<endl;
    threadObj.join();
    cout<<"Exit of Main function"<<endl;
    return 0;
}

3. 使用lambda表示创建线程

在这里插入图片描述
运行结果:
在这里插入图片描述

附上例代码:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

int main()
{
    
    
    int x=9;
    thread threadObj([]{
    
    
        for(int i=0;i<10000;i++)
            cout<<"Display Thread Executing"<<endl;
                     });
    for(int i=0;i<10000;i++)
        cout<<"Display From Main Thread"<<endl;
    threadObj.join();
    cout<<"Exiting from Main Thread"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43297891/article/details/113821892