全过程例程如下:
- void __fastcall TForm1::btn_1Click(TObject *Sender)
- {
- if (hthread == NULL) { // 不存在则创建线程
- hthread = CreateThread(
- (LPSECURITY_ATTRIBUTES)0, // default security attributes
- 0, // use default stack size
- (LPTHREAD_START_ROUTINE)funcproc, // thread function
- NULL, // argument to thread function
- 0, // use default creation flags
- NULL); // returns the thread identifier
- } else {
- ResumeThread(hthread);
- }
- }
- //---------------------------------------------------------------------------
- DWORD WINAPI funcproc()// thread data
- {
- int i;
- while(true)
- {
- i++;
- Sleep(50);
- Form1-> lbl_1-> Caption = i;
- }
- }
- void __fastcall TForm1::btn_2Click(TObject *Sender)
- {
- SuspendThread(hthread);
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::FormDestroy(TObject *Sender)
- {
- TerminateThread(hthread, (DWORD)0);
- CloseHandle(hthread);
- hthread = NULL;
- }
本文提供了一个使用C++在Windows环境下创建、暂停、恢复及终止线程的完整示例。通过两个按钮分别控制线程的启动与暂停,展示了线程生命周期管理的具体实现方式。
5375

被折叠的 条评论
为什么被折叠?



