// Thread.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN//不加载MFC需要的模块
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h> //conio是Console Input/Output(控制台输入输出)的简写,
//其中定义了通过控制台进行数据输入和数据输出的函数,
//主要是一些用户通过按键盘产生的对应操作,比如getch()函数等等
DWORD WINAPI ThreadFunc(LPVOID);
DWORD WINAPI ThreadFunc1(LPVOID);
int main(int argc, _TCHAR* argv[])
{
HANDLE hThread1;
HANDLE hThread2;
DWORD exitCode1 = 0;
DWORD exitCode2 = 0;
DWORD threadId;//因为createThread最后一个参数是LPDWORD类型的所以要写成&threadId的形式
hThread1 = CreateThread(NULL,0,ThreadFunc1,(LPVOID)1,0,&threadId);
if(hThread1)
{
printf("%d",threadId);
printf("Thread 1 launched/n");
}
hThread2 = CreateThread(NULL,0,ThreadFunc1,(LPVOID)1,0,&threadId);
if(hThread2)
{
printf("%d",threadId);
printf("Thread 2 launched/n");
}
for(;;)
{
printf("Press any key to exit../n");
_getch();
GetExitCodeThread(hThread1,&exitCode1);
GetExitCodeThread(hThread2,&exitCode2);
if(exitCode1 == STILL_ACTIVE)
puts("Thread1 is still running");
if(exitCode2 == STILL_ACTIVE)
puts("Thread2 is still running");
if(exitCode1 != STILL_ACTIVE && exitCode2 != STILL_ACTIVE){
puts("Thread1 and Thread2 are exited");
//break;
}
}
CloseHandle(hThread1);
CloseHandle(hThread2);
printf("Thread1 is returned %d/n",exitCode1);
printf("Thread2 is returned %d/n",exitCode2);
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
Sleep((DWORD)n*1000*2);//Sleep(a) a是毫秒级
printf("sleep is done,thread has been exited/n");//睡眠时间到了以后就醒了
return (DWORD)n*10;
}
DWORD WINAPI ThreadFunc1(LPVOID n)
{
while(true){
Sleep((DWORD)n*1000*2);//Sleep(a) a是毫秒级
printf("loop/n");//循环睡眠2秒 线程永久执行
}
}