c++ thread的用法有哪些

avatar
作者
筋斗云
阅读量:3

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

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

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!