C语言多线程创建

// 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秒 线程永久执行
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值