阅读量:113
C++中的线程库提供了多种方式来创建和管理线程。以下是一些常见的C++线程用法:
- 使用std::thread类创建线程:
#include
#include
void foo() {
std::cout << "Hello from thread!" << std class="hljs-function">int main() {
std::thread t(foo); // 创建一个新线程,并执行foo()函数
t.join(); // 等待线程t执行完毕
return 0;
}
- 使用lambda表达式创建线程:
#include
#include
int main() {
std::thread t([]() {
std::cout << "Hello from thread!" << std>;
t.join();
return 0;
}
- 使用std::async函数创建异步任务:
#include
#include
int foo() {
return 42;
}
int main() {
std::future<int> result = std::async(foo); // 创建一个异步任务,并返回一个std::future对象
std::cout << "Result: " << result class="hljs-built_in">get() << std class="hljs-comment">// 获取异步任务的结果
return 0;
}
- 使用std::mutex和std::lock_guard实现线程安全:
#include
#include
#include
std::mutex mtx;
void foo() {
std::lock_guard lock(mtx) ; // 获取互斥锁
std::cout << "Hello from thread!" << std class="hljs-function">int main() {
std::thread t(foo);
t.join();
return 0;
}
这些只是C++线程的一些常见用法,还有其他更高级的用法,如线程间的通信、线程池等。