std::thread t
时间: 2024-05-31 19:05:56 浏览: 20
std::thread是C++11标准中提供的一个线程库,用于创建和管理线程。可以通过std::thread t(函数名)来创建一个新的线程。其中,函数名为新线程所要执行的函数,可以是一个函数指针,也可以是一个函数对象,也可以是一个lambda表达式。创建线程后,可以通过t.join()或者t.detach()来等待线程结束或者将线程分离,使其独立运行。
如果使用join()函数等待线程结束,则必须保证在主线程中调用该函数之前,新线程已经运行完成;如果使用detach()函数,则新线程将成为守护线程,主线程和新线程各自独立运行。
需要注意的是,如果使用join()或者detach()之前未对std::thread对象进行初始化,则程序会抛出std::system_error异常。
相关问题
#include <iostream>#include <chrono>#include <thread>void increaseNumPerSecond(int& num) { while (true) { num++; std::this_thread::sleep_for(std::chrono::seconds(1)); }}int main() { int num = 0; std::thread t(increaseNumPerSecond, std::ref(num)); while (true) { std::cout << "Current number: " << num << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } t.join(); return 0;}
这是一个 C++ 程序,它创建了一个线程来每秒钟增加一个整数变量 num 的值,同时在主线程中每 500 毫秒输出 num 的当前值。程序的主要部分如下所示:
```c++
void increaseNumPerSecond(int& num) {
while (true) {
num++;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
int num = 0;
std::thread t(increaseNumPerSecond, std::ref(num));
while (true) {
std::cout << "Current number: " << num << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
t.join();
return 0;
}
```
首先定义了一个名为 `increaseNumPerSecond` 的函数,它接受一个整数引用作为参数,然后在一个无限循环中每秒钟将该整数加 1,并通过 `std::this_thread::sleep_for` 函数暂停 1 秒钟。
接下来是 `main` 函数,它声明了一个整数变量 `num`,并创建了一个新的线程 `t`,该线程将调用 `increaseNumPerSecond` 函数并传递 `num` 的引用作为参数。然后,在一个无限循环中,主线程每 500 毫秒输出 `num` 的当前值,并通过 `std::this_thread::sleep_for` 函数暂停 500 毫秒。最后,调用 `t.join()` 等待线程 `t` 结束,并返回 0。
这个程序可以用来演示如何使用 C++11 中的线程库创建一个简单的多线程程序。
std::thread返回值
std::thread返回值是一个线程的标识符,可以用来获取线程的ID。可以使用std::thread::get_id()函数来获取线程的ID,返回值类型为std::thread::id。如果需要将线程ID转换为string或int类型,可以使用相应的转换方法。
以下是一个示例代码,演示了如何获取线程ID并将其转换为string类型:
```cpp
#include <iostream>
#include <thread>
#include <sstream>
void threadFunction()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::thread::id myid = std::this_thread::get_id();
std::stringstream ss;
ss << myid;
std::string mystring = ss.str();
std::cout << "Thread ID: " << mystring << std::endl;
}
int main()
{
std::thread t(threadFunction);
t.join();
return 0;
}
```
运行以上代码,将会输出当前线程的ID。