Win32写多线程的时候经常需要线程同步,同步的方法很多,效率也不一样,这里介绍一种Event同步对象。
建立一个MFC基于Dialog的工程,界面如图:
// 线程部分 全部为全局变量和函数
const int MAX_THREAD = 3;
HANDLE hEvent = NULL; // handle to event object
HANDLE hThread[MAX_THREAD];
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
char buf[64];
HWND hList = ::GetDlgItem(theApp.m_pMainWnd->m_hWnd, IDC_LISTRESULT);
for(;;)
{
sprintf(buf, "Thread #%d Wait.", lpParameter);
ListBox_SetTopIndex(hList, ListBox_AddString(hList, buf));
WaitForSingleObject(hEvent, INFINITE);
sprintf(buf, "Thread #%d work.", lpParameter);
ListBox_SetTopIndex(hList, ListBox_AddString(hList, buf));
Sleep(0);
}
}
void StartThread(void)
{
for(int i = 0; i < MAX_THREAD; i++)
{
hThread[i] = CreateThread(NULL, 0, ThreadProc, (LPVOID)i, 0, NULL);
}
}
void KillThread(void)
{
for(int i = 0; i < MAX_THREAD; i++)
{
if(hThread[i] != NULL)
{
TerminateThread(hThread[i], 0);
WaitForSingleObject(hThread[i], INFINITE);
CloseHandle(hThread[i]);
hThread[i] = NULL;
}
}
}
// 按钮的一些消息函数
extern HANDLE hEvent;
void StartThread(void);
void KillThread(void);
void CEventDlg::OnBclean()
{
// TODO: Add your control notification handler code here
ListBox_ResetContent(::GetDlgItem(this->m_hWnd, IDC_LISTRESULT));
}
void CEventDlg::OnBpulse()
{
// TODO: Add your control notification handler code here
PulseEvent(hEvent);
}
void CEventDlg::OnBreset()
{
// TODO: Add your control notification handler code here
ResetEvent(hEvent);
}
void CEventDlg::OnBsetevent()
{
// TODO: Add your control notification handler code here
SetEvent(hEvent);
}
void CEventDlg::OnRauto()
{
// TODO: Add your control notification handler code here
KillThread();
if(hEvent != NULL)
{
CloseHandle(hEvent);
}
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
StartThread();
}
void CEventDlg::OnRmanual()
{
// TODO: Add your control notification handler code here
KillThread();
if(hEvent != NULL)
{
CloseHandle(hEvent);
}
hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
StartThread();
}
代码中使用了一些例如类似 ListBox_ResetContent 的宏,需要引用 windowsx.h 头文件。如果不使用这些宏,可以直接调用 SendMessage 函数。
本文地址:http://com.8s8s.com/it/it390.htm