使用系统调用CreateThread()创建一个子线程,并在子线程中显示;Thread is Running!。为了能让用户清楚地看到线程的运行情况,使用Sleep()使线程挂起5秒,之后使用ExitThread()撤销线程。使用dev c++写出上述问题的代码
时间: 2024-10-28 12:09:14 浏览: 53
在Dev C++中,你可以使用`<windows.h>`头文件中的函数来实现这个需求。以下是一个简单的示例代码:
```cpp
#include <iostream>
#include <windows.h>
// 定义线程函数
void* threadFunction(LPVOID lpParam) {
std::cout << "Thread is Running!\n";
Sleep(5000); // 挂起5秒钟
std::cout << "Exiting Thread...\n";
ExitThread(0); // 撤销线程并返回0
return NULL;
}
int main() {
// 创建一个线程
HANDLE hThread = CreateThread(NULL, 0, &threadFunction, NULL, 0, NULL);
if (hThread == INVALID_HANDLE_VALUE) {
std::cerr << "Error creating thread: " << GetLastError() << std::endl;
return 1;
}
// 等待线程结束
DWORD dwResult = WaitForSingleObject(hThread, INFINITE);
if (dwResult != WAIT_OBJECT_0) {
std::cerr << "Error waiting for thread: " << GetLastError() << std::endl;
} else {
CloseHandle(hThread);
std::cout << "Thread completed.\n";
}
return 0;
}
```
在这个代码中,`threadFunction()`作为参数传递给`CreateThread()`,它负责线程的具体工作。`WaitForSingleObject()`函数用于等待线程完成,而`CloseHandle()`关闭线程句柄。
阅读全文
相关推荐


















