创建多线程

本文最后更新于:2024年9月6日 晚上

C++中的多线程

传统的C++(C++11标准之前)中并没有引入线程这个概念,在C++11出来之前,如果我们想要在C++中实现多线程,需要借助操作系统平台提供的API,比如Linux的,或者windows下的 。

C++中线程的创建

使用std::thread类:这是C++11及以后版本推荐的方式。你可以直接创建一个std::thread对象来启动一个新的线程,并传递一个可调用对象(如函数、函数对象、Lambda表达式等)作为线程的执行体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>  
#include <thread>

void thread_function() {
std::cout << "Hello from thread!\n";
}

int main() {
// mian 所在的线程就是主线程(控制线程)
// 初始化一个子线程,让这个子线程执行thread_function函数
thread t(thread_function);
t.join(); // 阻塞当前线程,等待子线程执行完毕
print("main thread exit")
return 0;
}
  • mian 其实就是一个主线程
  • thread t(thread_function) 传入的参数为可调用对象:lambda表达式、仿函数
  • t.join() 阻塞当前线程,等待子线程执行完之后,主线程才继续往下执行

线程的可调用对象

在C++中,线程的可调用对象(callable object)可以是多种类型,包括但不限于:函数指针、成员函数指针、lambda表达式、函数对象(也称为仿函数或functor)以及绑定对象(通过std::bind创建)。以下是一些示例代码: - 函数指针

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>  
#include <thread>

void functionPointerTask() {
std::cout << "Function pointer task executed.\n";
}

int main() {
std::thread t(functionPointerTask);
t.join();
return 0;
}
- 成员函数指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>  
#include <thread>

class MyClass {
public:
void memberFunctionTask() {
std::cout << "Member function task executed.\n";
}
};

int main() {
MyClass obj;
std::thread t(&MyClass::memberFunctionTask, &obj); // 注意:需要传递对象指针
t.join();
return 0;
}
- Lambda表达式
1
2
3
4
5
6
7
8
9
10
#include <iostream>  
#include <thread>

int main() {
std::thread t([]() {
std::cout << "Lambda task executed.\n";
});
t.join();
return 0;
}
- 函数对象(仿函数)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>  
#include <thread>

struct Functor {
void operator()() {
std::cout << "Functor task executed.\n";
}
};

int main() {
Functor f;
std::thread t(f);
t.join();
return 0;
}
- 绑定对象(通过std::bind)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>  
#include <thread>
#include <functional>

void functionWithArgs(int a, int b) {
std::cout << "Function with args: " << a << ", " << b << ".\n";
}

int main() {
auto boundFunc = std::bind(functionWithArgs, 1, 2);
std::thread t(boundFunc);
t.join();
return 0;
}
请注意,从C++11开始,库是C++标准库的一部分,用于处理线程。在创建线程时,你需要传递一个可调用对象给std::thread的构造函数。可调用对象可以是上述任何一种类型。


创建多线程
https://zzmes.github.io/2024/09/06/thread-2/
作者
YangYangYang
发布于
2024年9月6日
许可协议