std::thread怎么用?
时间: 2023-07-06 15:03:48 浏览: 49
std::thread是C++11中的一个线程库,它可以用来创建并发执行的线程。下面是一个简单的例子:
```c++
#include <iostream>
#include <thread>
void threadFunc()
{
std::cout << "Hello from thread!" << std::endl;
}
int main()
{
std::thread t(threadFunc);
t.join();
return 0;
}
```
上面的代码创建了一个线程对象t,并将函数threadFunc作为参数传递给了它。线程对象t被启动后,将会调用threadFunc函数。join()函数会阻塞主线程,直到子线程执行完毕。
需要注意的是,线程在执行完毕之前必须调用join()函数或者detach()函数,否则会抛出std::system_error异常。如果调用detach()函数,则线程将变成后台线程,主线程不再等待该线程执行完毕。
```c++
#include <iostream>
#include <thread>
void threadFunc()
{
std::cout << "Hello from thread!" << std::endl;
}
int main()
{
std::thread t(threadFunc);
t.detach();
return 0;
}
```
上面的代码创建了一个线程对象t,并将函数threadFunc作为参数传递给了它。线程对象t被启动后,将会调用threadFunc函数。detach()函数会将线程变成后台线程,主线程不再等待该线程执行完毕。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)