欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Win32多线程之线程挂起**结束

程序员文章站 2022-06-10 20:49:15
...

这部分介绍线程“三态转换”的函数,创造,挂起,**,结束


#include "stdafx.h"

#include <windows.h>

#include <iostream>

using namespace std;



DWORD WINAPI FunOne(LPVOID param)

{

       int num1 = 0;

       while (true)

       {

               Sleep(1000);

               cout << "thread1 num "<<num1++<<endl;

       }

       return 0;

}



DWORD WINAPI FunTwo(LPVOID param)

{

       int num2 = 100;

       while (true)

       {

               Sleep(1000);

               cout << "thread2 num " << num2-- << endl;

       }

       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);



       HANDLE hand1 = CreateThread(NULL, 0, FunOne, NULL, CREATE_SUSPENDED, NULL);

       HANDLE hand2 = CreateThread( NULL, 0, FunTwo, NULL, 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;

}


运行结果

1
thread2 num thread1 num 0100

thread1 num thread2 num 99
1
thread1 num thread2 num 98
2
thread2 num 97
thread1 num 3
thread2 num 96
thread1 num 4
thread1 num 5
thread2 num 95
thread1 num 6
thread2 num 94
thread1 num 7
thread2 num 93
0
  • 主线程接收到1,**两个线程。两个线程以1000时间间隔,一个从0正数,一个从100倒计时。直到我输入任意其他字符,两个线程被挂起。

  • 注意到:输出有“混乱情况”,这是由于每个线程都是多个输出语句,并且没有被定义为一个不可分割的整体的“事务”,所以会有两个线程输出操作交替执行,出现像第一行输出那样的情况