租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c++ thread的用法有哪几种,c++中thread的参数

发布时间:2023-10-09 04:29:37

c++ thread的用法有哪几种

C++中的线程库提供了多种方式来创建和管理线程。以下是一些常见的C++线程用法:

  1. 使用std::thread类创建线程:
#include 
#include 
void foo() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);  // 创建一个新线程,并执行foo()函数
t.join();  // 等待线程t执行完毕
return 0;
}
  1. 使用lambda表达式创建线程:
#include 
#include 
int main() {
std::thread t([]() {
std::cout << "Hello from thread!" << std::endl;
});
t.join();
return 0;
}
  1. 使用std::async函数创建异步任务:
#include 
#include 
int foo() {
return 42;
}
int main() {
std::future result = std::async(foo);  // 创建一个异步任务,并返回一个std::future对象
std::cout << "Result: " << result.get() << std::endl;  // 获取异步任务的结果
return 0;
}
  1. 使用std::mutex和std::lock_guard实现线程安全:
#include 
#include 
#include 
std::mutex mtx;
void foo() {
std::lock_guard lock(mtx);  // 获得互斥锁
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);
t.join();
return 0;
}

这些只是C++线程的一些常见用法,还有其他更高级的用法,如线程间的通讯、线程池等。