#include <windows.h> #include <iostream> using namespace std; DWORD WINAPI FunOne(LPVOID param){ while(true) { Sleep(1000); cout<<"hello! "; } return 0; } DWORD WINAPI FunTwo(LPVOID param){ while(true) { Sleep(1000); cout<<"world! "; } return 0; } int main(int argc, char* argv[]) { int input=0; HANDLE hand1=CreateThread (NULL, 0, FunOne, (void*)&input, CREATE_SUSPENDED, NULL); HANDLE hand2=CreateThread (NULL, 0, FunTwo, (void*)&input, CREATE_SUSPENDED, NULL); while(true){ cin>>input; if(input==1) { ResumeThread(hand1); ResumeThread(hand2); } else { SuspendThread(hand1); SuspendThread(hand2); } }; TerminateThread(hand1,1); TerminateThread(hand2,1); return 0; }
时间: 2024-04-26 14:21:43 浏览: 134
这段代码创建了两个线程,分别执行 FunOne 和 FunTwo 函数,同时在主线程中等待用户输入。当用户输入 1 时,主线程会恢复两个线程的执行;当用户输入其他任意数字时,主线程会暂停两个线程的执行。用户可以通过输入 Ctrl+C(或者其他方式)来结束程序,并强制终止两个线程的执行。
需要注意的是,强制终止线程可能会导致一些问题,因此建议在正常情况下使用线程同步和协作来控制线程的执行,以保证程序的正确性和稳定性。
如果您有什么问题或者需要更详细的解释,请告诉我,我会尽力帮助您。
相关问题
#include <windows.h> #include <iostream> using namespace std; DWORD WINAPI FunOne(LPVOID param) { while (true) { Sleep(1000); cout << "hello! "; } return 0; } DWORD WINAPI FunTwo(LPVOID param) { while (true) { Sleep(1000); cout << "world! "; } return 0; } int main(int argc, char* argv[]) { int input = 0; HANDLE hand1 = CreateThread(NULL, 0, FunOne, (void*)&input, CREATE_SUSPENDED, NULL); HANDLE hand2 = CreateThread(NULL, 0, FunTwo, (void*)&input, CREATE_SUSPENDED, NULL); while (true) { cin >> input; if (input == 1) { ResumeThread(hand1); ResumeThread(hand2); } else { SuspendThread(hand1); SuspendThread(hand2); } }; TerminateThread(hand1, 1); TerminateThread(hand2, 1); return 0; }
这段代码的问题在于 `TerminateThread` 函数不应该被直接调用,因为它会强制终止线程,可能会导致资源无法正确释放,从而引起一些意外的问题。正确的做法应该是向线程发送一个终止信号,并让线程自己进行清理工作。
另外,这段代码中的 `while (true)` 循环没有进行任何阻塞,会导致 CPU 资源被大量占用。应该使用 `Sleep` 函数或者其他阻塞函数来降低 CPU 占用率。
下面是修改后的代码:
```
#include <windows.h>
#include <iostream>
using namespace std;
volatile bool g_bTerminate = false;
DWORD WINAPI FunOne(LPVOID param) {
while (!g_bTerminate) {
Sleep(1000);
cout << "hello! ";
}
return 0;
}
DWORD WINAPI FunTwo(LPVOID param) {
while (!g_bTerminate) {
Sleep(1000);
cout << "world! ";
}
return 0;
}
int main(int argc, char* argv[]) {
int input = 0;
HANDLE hand1 = CreateThread(NULL, 0, FunOne, (void*)&input, CREATE_SUSPENDED, NULL);
HANDLE hand2 = CreateThread(NULL, 0, FunTwo, (void*)&input, CREATE_SUSPENDED, NULL);
while (true) {
cin >> input;
if (input == 1) {
ResumeThread(hand1);
ResumeThread(hand2);
}
else {
SuspendThread(hand1);
SuspendThread(hand2);
}
};
g_bTerminate = true;
WaitForSingleObject(hand1, INFINITE);
WaitForSingleObject(hand2, INFINITE);
CloseHandle(hand1);
CloseHandle(hand2);
return 0;
}
```
在修改后的代码中,我们使用了一个全局变量 `g_bTerminate` 来表示线程是否应该终止。当用户输入 1 时,程序会恢复线程的执行;当用户输入其他值时,程序会挂起线程的执行。在程序退出时,我们先向线程发送终止信号,然后等待线程正常退出,并释放相关资源。
阅读全文
相关推荐















