序言
-
之前的文章介绍了 进程和线程的基本概念,以及 C语言多线程的基本函数
-
现对C++中多线程创建的几种方式做一个总结(学习记录)
1. 多线程
-
c++11中引入了线程类thread,头文件
#include <thread>
-
创建多线程的方法
std::thread threadName(函数名, 参数1, 参数2, ...)
std::thread threadName(functionName, leftValueArg, rightValueArg, std::ref(refArg), std::cref(constRefArg));
传参可以传左值、右值、引用使用std::ref、const引用使用std::cref;
参数先copy或move到std::thread对象,再move给函数 -
程序至少有一个线程(主线程),一旦创建了std::thread对象也就是在主线程外创建了一个子线程,其立刻开始运行
2. 多线程的创建
常见的线程创建方式如下:
1. 普通函数
2. 成员函数
3. 仿函数
4. lambda函数
- 线程创建方式1:普通函数
#include <iostream>
#include <thread>
void Function(int a, int& b)
{
a = 2;
b = 2;
}
int main()
{
int a = 1;
int b = 1;
// create sub-thread
std::thread newThread(Function, a, std::ref(b));
std::cout << a << " " << b << std::endl;
// main thread waiting for sub-thread to finish
newThread.join();
return 0;
}
// 编译运行
g++ --o main main.cpp -pthread
- 线程创建方式2:成员函数
#include <iostream>
#include <thread>
class MyClass {
public:
void Function(const int& num)
{
std::cout << "I am " << num << " yeas old" << std::endl;
}
};
int main()
{
MyClass object;
int num = 29;
// create sub-thread
std::thread newThread(&MyClass::Function, &object, std::cref(num));
// main thread waiting for sub-thread to finish
newThread.join();
return 0;
}
- 线程创建方式3:仿函数
#include <iostream>
#include <thread>
class MyClass {
public:
void operator() (int& num)
{
std::cout << "sub-thread start" << std::endl;
num = 30;
std::cout << "sub-thread end" << std::endl;
}
};
int main()
{
std::cout << "main thread start" << std::endl;
MyClass object;
int num = 29;
std::cout << "num = " << num << std::endl;
// create sub-thread
std::thread newThread(object, std::ref(num));
// std::thread newThread(MyClass(), std::ref(num)); 也可
// main thread waiting for sub-thread to finish
newThread.join();
std::cout << "num = " << num << std::endl;
std::cout << "main thread end" << std::endl;
return 0;
}
// 上面的例子,也可如下实现
...
int main()
{
// MyClass object; // no need to create object
std::thread newThread(MyClass(), std::ref(num));
...
}
- 线程创建方式4:匿名函数lambda
#include <iostream>
#include <thread>
int main()
{
auto function = [](int a) { std::cout << a << '\n'; };
// create sub-thread
std::thread newThread(function, 10);
newThread.join();
return 0;
}
// 或以如下方式调用lambda函数
#include <iostream>
#include <thread>
int main()
{
// create sub-thread
std::thread newThread([](int a) {std::cout << a << std::endl;}, 10);
newThread.join();
return 0;
}
参考文章:
多线程与单线程的对比
线程创建的几种方式
cpp官网线程创建的几种方式
ros多线程创建
created by shuaixio, 2022.04.30