VC语言

本类阅读TOP10

·VC++ 学习笔记(二)
·用Visual C++打造IE浏览器(1)
·每个开发人员现在应该下载的十种必备工具
·教你用VC6做QQ对对碰外挂程序
·Netmsg 局域网聊天程序
·Windows消息大全
·VC++下使用ADO编写数据库程序
·VC++学习笔记(四)
·非法探取密码的原理及其防范
·怎样在VC++中访问、修改注册表

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
使用Event同步线程

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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 函数。




相关文章

相关软件