在C++中创建多线程通常使用 #include<thread>
,这是C++11标准引入的一个头文件,方便线程的使用。利用多核处理器的能力,通过多线程可以同时执行多个任务,提高程序的执行效率。
一、使用<thread>直接创建
直接使用<thread>创建一个线程所绑定的线程函数不允许带参数
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(thread_function); // 创建线程
t.join(); // 等待线程结束
return 0;
}
二、 使用 std::thread
与 lambda 表达式
使用lambda创建线程可允许线程函数带参数
#include <iostream>
#include <thread>
void thread_function(int x) {
std::cout << "The value of x is: " << x << std::endl;
}
int main() {
int x = 5;
std::thread t([&x](){
thread_function(x);
})
t.join();
return 0;
}
三、使用 std::async
创建线程
std::async
是 C++11 引入的一个函数模板,它用于异步地执行函数或 lambda 表达式,并返回一个 std::future
对象,可以通过这个对象来获取结果或等待结果。
#include <iostream>
#include <future>
int async_function() {
return 10;
}
int main() {
auto result = std::async(std::launch::async, async_function);
// // 获取异步执行的结果
std::cout << "Result from async function: " << result.get() << std::endl;
return 0;
}