//Use MFC in a Static Library #include "stdafx.h" #include <windows.h> #include "stdio.h" #include "afxmt.h" int i=2; CCriticalSection Cmysection; DWORD WINAPI clientthread(LPVOID lpparam) { int num=(int)lpparam; while(true) { Cmysection.Lock(); //可以使Cmysection.Lock()到Cmysection.Unlock(); //这段代码在同一时刻只允许一个线程操作 if(num==1) printf("hthread1在操作\t"); else printf("hthread2在操作\t"); Sleep(500); i++; printf("%d,%d\n",num,i); Cmysection.Unlock(); } return 0; } int main(int argc, char* argv[]) { int num = 1; HANDLE hthread1,hthread2; DWORD dwthreadid; char szBuff[MAX_PATH]; hthread1=CreateThread(NULL,0,clientthread,(LPVOID)num,0,&dwthreadid); if(hthread1==NULL) { printf("fail55\n"); } hthread2=CreateThread(NULL,0,clientthread,(LPVOID)(num+1),0,&dwthreadid); if(hthread2==NULL) { printf("fail55\n"); } gets(szBuff); CloseHandle(hthread1); CloseHandle(hthread2); return 0; }
5
3