c++11 std::thread
时间: 2024-11-06 07:12:22 浏览: 36
C++11引入了`std::thread`库,这是一个用于处理线程的标准库。它提供了一种方便的方式来创建、管理和同步线程,使得并发编程变得更加简单。`std::thread`类允许你在代码中创建一个新的线程,并将一个函数或者方法作为目标线程的任务(也称为线程执行体)。使用`std::thread`的主要步骤包括:
1. 创建线程:通过`std::thread`构造函数指定一个函数指针以及需要传递给该函数的参数。例如:
```cpp
void my_function(int param) {
// 线程执行的具体代码
}
std::thread thread_instance(my_function, 42);
```
2. 启动线程:创建线程后,需要调用它的`start()`方法启动线程。这个操作是异步的,意味着主线程会继续执行而不会等待新线程完成。
3. 等待线程结束:如果你想让主线程等待新线程执行完毕,可以使用`join()`方法。如果不想阻塞,也可以使用`detach()`方法使线程独立运行。
4. 错误检查:在使用`std::thread`时,要注意检查异常,因为线程的生命周期可能会遇到各种错误。
相关问题
windows C++ std::thread
### 使用 `std::thread` 进行多线程编程
在 Windows 环境下使用 C++ 的 `std::thread` 库可以方便地创建和管理多个线程。下面是一个简单的例子来展示如何实现一个多线程程序。
#### 创建并启动新线程
通过实例化 `std::thread` 对象并将目标函数传递给它作为参数,即可轻松创建新的工作线程:
```cpp
#include <iostream>
#include <thread>
void task(int id) {
std::cout << "Thread ID: " << id << ", this_thread::get_id(): "
<< std::this_thread::get_id() << '\n';
}
int main() {
// Create two threads that execute 'task'
std::thread t1(task, 1);
std::thread t2(task, 2);
// Wait for both threads to finish their execution before continuing.
if (t1.joinable()) t1.join();
if (t2.joinable()) t2.join();
return 0;
}
```
此代码片段展示了两个独立的工作线程被创建出来执行相同的任务函数[^1]。
#### 处理返回值与共享数据
当需要处理来自不同线程的结果或共享某些资源时,则可能需要用到互斥锁 (`mutex`) 来保护这些临界区的数据访问安全;也可以考虑采用更高级别的同步机制如条件变量(`condition_variable`) 或者原子操作(`atomic<T>`).
对于想要获取子线程计算结果的情况,可以通过引用传参的方式让子线程修改外部定义好的容器内的元素,或者利用 `future/promise` 组件来进行异步通信。
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <chrono>
// A simple function which takes longer time and returns result via reference parameter
void longComputation(std::vector<int>& vec){
auto start = std::chrono::steady_clock::now();
while(true){
auto end = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(end-start).count()>3){break;}
}
vec.push_back(42); // Add computed value into vector after computation completes
}
int main(){
std::vector<int> results;
// Launching multiple threads with different tasks...
std::thread thd(longComputation,std::ref(results));
// Do other things here...
// Join the thread back when done working elsewhere
thd.join();
// Print out final outcome from all computations performed by launched threads
for(auto& item :results){
std::cout<<item<<"\n";
}
return 0;
}
```
这段示范说明了怎样在一个单独的进程中并发运行几个不同的活动,并且收集它们产生的输出.
c++std::thread
### C++ 中 `std::thread` 的使用方法
#### 创建线程
为了创建一个新的线程,可以实例化一个 `std::thread` 对象并传递给其构造函数想要在线程中运行的任务。这个任务通常是一个函数或 lambda 表达式。
```cpp
#include <iostream>
#include <thread>
void backgroundTask() {
std::cout << "Running on a separate thread." << std::endl;
}
int main() {
std::thread t(backgroundTask);
}
```
当不再需要线程时,应该调用 `join()` 或者 `detach()` 方法来释放资源[^1]。
#### 加入线程 (`join`)
通过调用 `join()` 可以等待线程完成工作后再继续执行后续代码:
```cpp
t.join();
// 主线程在此处暂停直到子线程结束
```
#### 分离线程 (`detach`)
分离线程意味着让新启动的线程独立于主线程之外运行,而不需要显式的同步机制:
```cpp
t.detach();
// 子线程将继续异步执行直至完成自己的生命周期
```
#### 获取线程ID
可以通过 `get_id()` 函数获得当前线程的身份标识符:
```cpp
auto id = t.get_id();
std::cout << "Thread ID is " << id << std::endl;
```
#### 检测是否可加入
要判断某个线程对象关联的实际操作系统级别的线程是否存在且未被回收,则可以用 `joinable()` 成员函数来进行测试:
```cpp
if (t.joinable()) {
// 如果该条件成立则表示存在有效的工作线程可供连接
}
```
#### Lambda表达式作为参数传入
也可以利用lambda表达式向线程传递额外的数据,在下面的例子中展示了如何捕获局部变量以及外部作用域内的数据结构:
```cpp
#include <iostream>
#include <string>
#include <thread>
int main(){
int local_state=0;
auto func=[&local_state]() mutable -> void{
++local_state;
std::cout<<"Local state:"<<local_state<<'\n';
};
std::thread(func).join();
}
```
#### 处理返回值
对于那些有返回值得情况,我们可以借助 `std::promise`, `std::future` 和 `std::packaged_task` 来实现跨线程间的安全通信与协调:
```cpp
#include <iostream>
#include <memory>
#include <future>
#include <utility>
#include <functional>
using namespace std;
double divide(double a,double b){
if(b==0) throw runtime_error("Division by zero!");
return a/b;
}
int main(){
packaged_task<double(double,double)> task(divide);
future<double> result=task.get_future();
thread td(move(task),2.0,4.0);
try{
cout<<result.get()<<endl;//阻塞在这里直到得到结果
}
catch(exception const&e){
cerr<<e.what()<<endl;
}
td.join();
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)