Window API (八)多线程的挂起、恢复、切换、终止线程

时间:2021-11-24 21:20:42

     只会线程的创建和退出还是不够的,一些基本操作也得会......

    创建两个线程。创建时,一个运行一个挂起。然后唤醒挂起的,挂起运行的。运行一段时间后,终止运行的,唤醒挂起的Window API (八)多线程的挂起、恢复、切换、终止线程  哈 听上去挺乱,还是看程序简单......

 

#include<stdio.h>
#include<windows.h>


DWORD WINAPI ThreadProc(LPVOID lpParam)
{
LPDWORD pData;
DWORD i=0;
pData=(LPDWORD)lpParam;
for(i;i<10;i++)
{
Sleep(100);
printf("TID = %u ,\t Parameters = %u\t i = %u\n",
GetCurrentThreadId(),*pData,i);
}
ExitThread(i);
return 0;
}

void main()
{
DWORD dwData1;
DWORD dwData2;
DWORD dwThreadId[2];
HANDLE hThread[2];
dwData1=1;
hThread[0] = CreateThread(
NULL,0,
ThreadProc,&dwData1,
CREATE_SUSPENDED,
&dwThreadId[0]);
if(hThread[0] == NULL)
{
ExitProcess(0);
}

dwData2 = 2;
hThread[1]=CreateThread(
NULL,0,
ThreadProc,&dwData2,
0,
&dwThreadId[1]);
if(hThread[1] == NULL)
{
ExitProcess(1);
}
Sleep(200);
//启动0
ResumeThread(hThread[0]);
//挂起1
SuspendThread(hThread[1]);
//正好500会造成少输出一次
Sleep(510);
//输出五次就停止
TerminateThread(hThread[0],0);
//启动1
ResumeThread(hThread[1]);
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
}


输出结果:

TID = 2752 ,     Parameters = 2  i = 0   --注意,这里只运行一次
TID = 4872 , Parameters = 1 i = 0
TID = 4872 , Parameters = 1 i = 1
TID = 4872 , Parameters = 1 i = 2
TID = 4872 , Parameters = 1 i = 3
TID = 4872 , Parameters = 1 i = 4
TID = 2752 , Parameters = 2 i = 1
TID = 2752 , Parameters = 2 i = 2
TID = 2752 , Parameters = 2 i = 3
TID = 2752 , Parameters = 2 i = 4
TID = 2752 , Parameters = 2 i = 5
TID = 2752 , Parameters = 2 i = 6
TID = 2752 , Parameters = 2 i = 7
TID = 2752 , Parameters = 2 i = 8
TID = 2752 , Parameters = 2 i = 9


     本篇博客出自  阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/7084488