// 1. 使用 std::thread 创建线程
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Thread using function pointer." << std::endl;
}
int main() {
std::thread t(threadFunction);
t.join(); // 等待线程结束
return 0;
}
// 2. 使用 lambda 表达式创建线程
#include <iostream>
#include <thread>
int main() {
std::thread t([](){
std::cout << "Thread using lambda expression." << std::endl;
});
t.join(); // 等待线程结束
return 0;
}
// 3. 使用类成员函数创建线程
#include <iostream>
#include <thread>
class MyClass {
public:
void memberFunction() {
std::cout << "Thread using member function." << std::endl;
}
};
int main() {
MyClass obj;
std::thread t(&MyClass::memberFunction, &obj);
t.join(); // 等待线程结束
return 0;
}
// 4. 使用 std::async 创建异步任务
#include <iostream>
#include <future>
int asyncFunction() {
std::cout << "Thread using std::async." << std::endl;
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, asyncFunction);
std::cout << "Result from async call: " << result.get() << std::endl; // 等待并获取结果
return 0;
}
使用 std::thread
创建线程:
std::thread
构造函数来创建线程。join()
方法用于等待线程完成。使用 lambda 表达式创建线程:
使用类成员函数创建线程:
std::thread
构造函数来实现。使用 std::async
创建异步任务:
std::async
提供了一种更高级的方式来启动异步任务,并且可以方便地获取任务的结果。std::future
用于接收异步任务的返回值。上一篇:c++ dynamic_cast
下一篇:c++ *
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站