I agree with xxqfperfect(勇仔), you should spend some time on Operate System. First, you get the basic idea about the synchcronization and mutex. Second, you find some demo. Search key, such as"CreateMutex, CreateSemaphore, CreateEvent". Eventually, write code by yourself.
<Windows核心编程>
void Thread(PVOID pvoid)
{
while(bGoing)
{
WaitForSingleObject(mutex);
...do someting.....
ReleaseMutex(mutex);
}
}
这些在MFC中都有相应的封装类,CMutex CEvent等
看看候捷的Win32多线程程序设计,比较好
// 临界区结构对象
CRITICAL_SECTION g_cs;
// 共享资源
char g_cArray[10];
UINT ThreadProc10(LPVOID pParam)
{
// 进入临界区
EnterCriticalSection(&g_cs);
// 对共享资源进行写入操作
for (int i = 0; i < 10; i++)
{
g_cArray[i] = 'a';
Sleep(1);
}
// 离开临界区
LeaveCriticalSection(&g_cs);
return 0;
}
UINT ThreadProc11(LPVOID pParam)
{
// 进入临界区
EnterCriticalSection(&g_cs);
// 对共享资源进行写入操作
for (int i = 0; i < 10; i++)
{
g_cArray[10 - i - 1] = 'b';
Sleep(1);
}
// 离开临界区
LeaveCriticalSection(&g_cs);
return 0;
}
……
void CSample08View::OnCriticalSection()
{
// 初始化临界区
InitializeCriticalSection(&g_cs);
// 启动线程
AfxBeginThread(ThreadProc10, NULL);
AfxBeginThread(ThreadProc11, NULL);
// 等待计算完毕
Sleep(300);
// 报告计算结果
CString sResult = CString(g_cArray);
AfxMessageBox(sResult);
}
First, you get the basic idea about the synchcronization and mutex.
Second, you find some demo. Search key, such as"CreateMutex, CreateSemaphore, CreateEvent".
Eventually, write code by yourself.