c++多綫程Thread怎麽關閉
时间: 2023-11-03 17:04:16 浏览: 85
在 C++ 中,关闭线程的方法取决于您创建线程的方式。如果您使用 C++11 中的 std::thread 创建线程,则可以使用 std::thread::join() 函数来等待线程完成并关闭它。示例代码如下:
```c++
#include <iostream>
#include <thread>
void foo() {
std::cout << "Thread is running...\n";
// 线程执行的代码
}
int main() {
std::thread t(foo); // 创建线程
// 等待线程执行完毕并关闭
t.join();
std::cout << "Thread has been closed.\n";
return 0;
}
```
如果您使用 Windows API 创建线程,则可以使用 TerminateThread() 函数来立即终止线程。但是,这种方法可能会导致资源泄漏,因此建议在可能的情况下使用 std::thread::join() 函数。示例代码如下:
```c++
#include <iostream>
#include <Windows.h>
DWORD WINAPI foo(LPVOID lpParam) {
std::cout << "Thread is running...\n";
// 线程执行的代码
return 0;
}
int main() {
HANDLE hThread = CreateThread(NULL, 0, foo, NULL, 0, NULL); // 创建线程
// 等待线程执行完毕并关闭
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
std::cout << "Thread has been closed.\n";
return 0;
}
```