c++ thread的用法有哪些
C++中的线程库提供了多种方式来创建和管理线程。以下是一些常见的C++线程用法:
- 使用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;
}
- 使用lambda表达式创建线程:
#include <iostream>
#include <thread>
int main() {
std::thread t([]() {
std::cout << "Hello from thread!" << std::endl;
});
t.join();
return 0;
}
- 使用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;
}
- 使用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++线程的一些常见用法,还有其他更高级的用法,如线程间的通信、线程池等。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:美国服务器如何提升工作效率 下一篇:python怎么将灰度图像二值化
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。