C++ 创建一个std :: thread
示例
在C++中,使用std::thread类创建线程。线程是独立的执行流程;这类似于让助手同时执行另一任务。当线程中的所有代码执行完后,它终止。创建线程时,您需要传递一些要在其上执行的内容。您可以传递给线程的一些信息:
免费功能
会员职能
函子对象
Lambda表达式
自由函数示例-在单独的线程上执行函数(实时示例):
#include <iostream>
#include <thread>
void foo(int a)
{
std::cout << a << '\n';
}
int main()
{
//创建并执行线程
std::thread thread(foo, 10); //foo是要执行的函数,10是
//传递给它的论点
//继续;线程分别执行
//等待线程完成;我们待在这里直到完成
thread.join();
return 0;
}成员函数示例-在单独的线程上执行成员函数(实时示例):
#include <iostream>
#include <thread>
class Bar
{
public:
void foo(int a)
{
std::cout << a << '\n';
}
};
int main()
{
Bar bar;
//创建并执行线程
std::thread thread(&Bar::foo, &bar, 10); //将10传递给成员函数
//成员函数将在单独的线程中执行
//等待线程完成,这是一个阻塞操作
thread.join();
return 0;
}Functor对象示例(实时示例):
#include <iostream>
#include <thread>
class Bar
{
public:
void operator()(int a)
{
std::cout << a << '\n';
}
};
int main()
{
Bar bar;
//创建并执行线程
std::thread thread(bar, 10); //将10传递给仿函数对象
//functor对象将在单独的线程中执行
//等待线程完成,这是一个阻塞操作
thread.join();
return 0;
}Lambda表达式示例(实时示例):
#include <iostream>
#include <thread>
int main()
{
auto lambda = [](int a) { std::cout << a << '\n'; };
//创建并执行线程
std::thread thread(lambda, 10); //将10传递给lambda表达式
//lambda表达式将在单独的线程中执行
//等待线程完成,这是一个阻塞操作
thread.join();
return 0;
}