#include "stdafx.h" #include<windows.h> #include<process.h> DWORD WINAPI mywork1( LPVOID lpParameter) { printf("CreatThread thread %i\n",GetCurrentThreadId()); return 0; } unsigned int __stdcall mywork2(void *data) { printf("_beginthreadex thread %i\n",GetCurrentThreadId()); return 0; } void mywork3(void * data) { printf("_beginthreade thread %i\n",GetCurrentThreadId()); } int _tmain(int argc, _TCHAR* argv[]) { HANDLE h1,h2,h3; h1 = CreateThread(0,0,mywork1,0,0,0); h2 = (HANDLE)_beginthreadex(0,0,&mywork2,0,0,0); WaitForSingleObject(h2,INFINITE); CloseHandle(h2); h3 = (HANDLE)_beginthread(&mywork3,0,0); getchar(); return 0; }
#include "stdafx.h" #include <windows.h> #include <process.h> #include <math.h> volatile int counter = 0; CRITICAL_SECTION critical; int isprime(int number) { int i; for( i = 2; i < (int) (sqrt((float)number) + 1.0); i++) { if(number % i == 0 ){ return 0;} } return 1; } unsigned int __stdcall test(void *) { while (counter < 100) { while ( !TryEnterCriticalSection( &critical)){} int number = counter++; LeaveCriticalSection( &critical); printf("ThreadID %i; value = %i, is prime = %i\n", GetCurrentThreadId(), number, isprime(number)); } return 0; } /* unsigned int __stdcall test(void *) { while (counter < 100) { EnterCriticalSection( &critical); int number = counter++; LeaveCriticalSection( &critical); printf("ThreadID %i; value = %i, is prime = %i\n", GetCurrentThreadId(), number, isprime(number)); } return 0; } */ int _tmain(int argc, _TCHAR* argv[]) { HANDLE h1, h2; InitializeCriticalSection( &critical); h1 = (HANDLE)_beginthreadex(0, 0, &test,(void*)0, 0, 0); h2 = (HANDLE)_beginthreadex(0, 0, &test,(void*)0, 0, 0); WaitForSingleObject(h1,INFINITE);// WaitForSingleObject(h2,INFINITE); CloseHandle(h1); CloseHandle(h2); getchar(); DeleteCriticalSection( &critical); return 0; }
参考文献: