多线程2 _beginthreadex

#include "stdafx.h"
#include <string>
#include <stdio.h>
#include <windows.h>
#include <process.h>

using namespace std;

typedef struct ThreadX
{
 int a;
 int b;
};

unsigned _stdcall func(void *pthis)
{
 ThreadX *pthx = (ThreadX *)pthis;
 printf("the members are %d,%d\n",pthx->a,pthx->b);
 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 ThreadX *thread1 = new ThreadX;
 thread1->a = 2;
 thread1->b = 4;
 HANDLE hth1 = (HANDLE)_beginthreadex(NULL,0,func,thread1,CREATE_SUSPENDED,NULL);
 if(hth1 == 0)
  printf("Failed to create thread\n");
 DWORD dwExitCode;
 GetExitCodeThread(hth1,&dwExitCode);
 printf("initial thread 1 exit code = %u\n",dwExitCode);

 ThreadX *thread2 = new ThreadX;
 thread2->a = 6;
 thread2->b = 9;
 HANDLE hth2 = (HANDLE)_beginthreadex(NULL,0,func,thread2,CREATE_SUSPENDED,NULL);
 if(hth2 == 0)
  printf("Failed to create thread\n");
 GetExitCodeThread(hth1,&dwExitCode);
 printf("initial thread 2 exit code = %u\n",dwExitCode);

 ResumeThread(hth1);
 ResumeThread(hth2);

 WaitForSingleObject(hth1,INFINITE);
 WaitForSingleObject(hth2,INFINITE);

 GetExitCodeThread(hth1,&dwExitCode);
 printf("initial thread 1 exit code = %u\n",dwExitCode);
 GetExitCodeThread(hth1,&dwExitCode);
 printf("initial thread 2 exit code = %u\n",dwExitCode);

 CloseHandle(hth1);
 CloseHandle(hth2);

 delete thread1;
 thread1 = NULL;
 delete thread2;
 thread2 = NULL;

 printf("Primary thread terminating.\n");
 return 0;

}

你可能感兴趣的:(多线程,职场,休闲)