中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > Web开发 > JavaScripts > 综合文章
使用Event同步线程
作者:佚名 时间:2005-02-22 11:03 出处:互连网 责编:chinaitpower
              摘要:使用Event同步线程

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

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有