// 20171226_02.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #include <stdio.h> #include <windows.h> HWND hEdit; CRITICAL_SECTION cs1; CRITICAL_SECTION cs2; DWORD WINAPI ThreadProc1( LPVOID lpParameter // thread data ) { TCHAR numStr[10]={0}; memset(numStr,0,10); DWORD num = 0; DWORD nIndex = 0; while(nIndex<10000) { EnterCriticalSection(&cs1); EnterCriticalSection(&cs2); GetWindowText(hEdit,numStr,10); sscanf(numStr,"%d",&num); num++; nIndex++; memset(numStr,0,10); sprintf(numStr,"%d",num); SetWindowText(hEdit,numStr); LeaveCriticalSection(&cs2); LeaveCriticalSection(&cs1); } return 0; } DWORD WINAPI ThreadProc2( LPVOID lpParameter // thread data ) { TCHAR numStr[10]={0}; memset(numStr,0,10); DWORD num = 0; DWORD nIndex = 0; while(nIndex<10000) { EnterCriticalSection(&cs2); EnterCriticalSection(&cs1); GetWindowText(hEdit,numStr,10); sscanf(numStr,"%d",&num); num++; nIndex++; memset(numStr,0,10); sprintf(numStr,"%d",num); SetWindowText(hEdit,numStr); LeaveCriticalSection(&cs1); LeaveCriticalSection(&cs2); } return 0; } BOOL CALLBACK MainDialogProc( HWND hwndDlg, // handle to dialog box UINT uMsg, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ){ switch(uMsg) { case WM_INITDIALOG: { //初始化令牌 InitializeCriticalSection(&cs1); InitializeCriticalSection(&cs2); hEdit = GetDlgItem(hwndDlg,IDC_EDIT); SetWindowText(hEdit,"0"); break; } case WM_CLOSE: { DeleteCriticalSection(&cs1); DeleteCriticalSection(&cs2); EndDialog(hwndDlg,0); break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_BUTTON1: { //MessageBox(0,0,0,0); HANDLE hThread1 = CreateThread(NULL,0,ThreadProc1,0,0,NULL); break; } case IDC_BUTTON2: { //MessageBox(0,0,0,0); HANDLE hThread2 = CreateThread(NULL,0,ThreadProc2,0,0,NULL); break; } } } } return FALSE; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG_MAIN),NULL,MainDialogProc); return 0; }
0则评论给“简单死锁案例测试”