// 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 cs; 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(&cs); GetWindowText(hEdit,numStr,10); sscanf(numStr,"%d",&num); num++; nIndex++; memset(numStr,0,10); sprintf(numStr,"%d",num); SetWindowText(hEdit,numStr); LeaveCriticalSection(&cs); } 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(&cs); GetWindowText(hEdit,numStr,10); sscanf(numStr,"%d",&num); num++; nIndex++; memset(numStr,0,10); sprintf(numStr,"%d",num); SetWindowText(hEdit,numStr); LeaveCriticalSection(&cs); } 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(&cs); hEdit = GetDlgItem(hwndDlg,IDC_EDIT); SetWindowText(hEdit,"0"); break; } case WM_CLOSE: { 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则评论给“简单线程安全测试”