多執行緒 變數 加鎖問題
阿新 • • 發佈:2019-01-04
int g_test;
int temp;
BOOL g_bRunning;
DWORD WINAPI thWriteProc1(LPVOID lParam)
{
while(g_bRunning)
{
g_test = 12345678;
Sleep(1);
}
return 0;
}
DWORD WINAPI thWriteProc2(LPVOID lParam)
{
while(g_bRunning)
{
g_test = 13579246;
Sleep(1);
}
return 0;
}
DWORD WINAPI thReadProc(LPVOID lParam)
{
while(g_bRunning)
{
temp = g_test;//讀取值 if ( temp != 12345678 && temp != 13579246 )
{
g_bRunning = FALSE;
CString str;
str.Format("read error!%d", temp);
AfxMessageBox(str);
break ;
}
Sleep(1);
}
return 0;
}
void CTestMultiyAccessIntDlg::OnButton1()
{
g_bRunning = TRUE;
for ( int i = 0; i < 50; i++ )
{
//建立50個寫執行緒1 CreateThread( NULL, 0, thWriteProc1, NULL, 0, NULL );
}
for ( int i = 0; i < 50; i++ )
{
//建立50個寫執行緒2 CreateThread( NULL, 0, thWriteProc2, NULL, 0, NULL );
}
for ( int i = 0; i < 50; i++ )
{
//建立50個讀執行緒 CreateThread( NULL, 0, thReadProc, NULL, 0, NULL );
}
}