#include "stdafx.h"
#include <afxwin.h>
#include <windows.h>
CRITICAL_SECTION g_cs;
char g_cArray[10];
UINT ThreadProcFirst(LPVOID pParam);
UINT ThreadProcSecond(LPVOID pParam);
int main(int argc, char* argv[])
{
InitializeCriticalSection(&g_cs);
/*注意: 线程First与线程Second启动顺序不定*/
AfxBeginThread(ThreadProcFirst, NULL);
AfxBeginThread(ThreadProcSecond, NULL);
Sleep(300);
/*Sleep(1000);*/
CString strResult = CString(g_cArray);
AfxMessageBox(strResult);
return 0;
}
UINT ThreadProcFirst(LPVOID pParam)
{
EnterCriticalSection(&g_cs);
printf("First");
for (int i = 0; i < 10; ++i)
{
g_cArray[i] = 'a';
Sleep(1);
}
LeaveCriticalSection(&g_cs);
return 0;
}
UINT ThreadProcSecond(LPVOID pParam)
{
EnterCriticalSection(&g_cs);
printf("Second");
for (int i = 0; i < 10; ++i)
{
g_cArray[10-i-1] = 'b';
Sleep(1);
}
LeaveCriticalSection(&g_cs);
return 0;
}
|
结果1:
FirstSecond
bbbbbbbbbb
结果2:
FirstSecond
aaaabbbbbb
结果3:
SecondFirst
aaaaaaaaaa
根据Sleep()的延迟结果可能不同.
当Sleep(1)时, 结果可能为 空 或者 a 或者 b 或者 其他值.
阅读(389) | 评论(0) | 转发(0) |