用两个线程实现1-100之间数的输出
主要关键是实现线程的同步访问,程序用到了事件对象和CreateThread函数。
#include <stdio.h> #include <windows.h> int n=0; HANDLE hEvent; DWORD WINAPI ThreadFunc(LPVOID lpParam) { WaitForSingleObject(hEvent,INFINITE);//实现互斥访问 while(n<100) { Sleep(100); n++; printf("the count=%d\n",n); } SetEvent(hEvent); } DWORD WINAPI Add(LPVOID lpParam) { WaitForSingleObject(hEvent,INFINITE); while(n<100) { Sleep(100); n++; printf("the count=%d\n",n); } SetEvent(hEvent); } int main() { HANDLE hThread,hThread1; DWORD dwThreadId,dwThreadId1; hEvent=CreateEvent(NULL,FALSE,TRUE,NULL);//创建事件对象 hThread=CreateThread(NULL,NULL,ThreadFunc,NULL,0,&dwThreadId);//创建线程 hThread1=CreateThread(NULL,NULL,Add,NULL,0,&dwThreadId1); printf("the dwThreadId =%d\n",dwThreadId); printf("the dwThreadId =%d\n",dwThreadId1); WaitForSingleObject(hThread,INFINITE); WaitForSingleObject(hThread1,INFINITE); CloseHandle(hThread);//关闭线程句柄 CloseHandle(hThread1); return 0; }