程序实现的要求:
我的程序中有一个主线程,N个工作线程。主线程负责收集数据,然后分派给不同的工作线程去处理。我在程序中使用了PostThreadMessage()来通知相应的线程处理数据,而工作线程使用GetMessage()来进行相应。
伪代码:
代码流程如下:
CreateThread(main);//主线程;
for (int i=0;i<10;i++)//假设10个工作线程
{
CreateThread(work); //这里同时记录工作线程的ThreadID;
}
ThreadMain()
{
if (条件符合某个线程的要求)
{
while(!PostThreadMessage(WorkID,MSG,parm,0)) sleep(0);//投递消息通知给相应的工作线程
}
}
ThreadWork()
{
while(true)
{
iRet = GetMessage(msg,NULL,0,0);
{
......此处省略对iRet的判断
if (msg.message = MY_MSG)
{
进行相应处理。。。
}
}
}
}
编译通过的源代码:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <map>
#include <iostream>
using namespace std;
typedef map<int,DWORD> value_map;
typedef value_map::value_type valType;
#define WM_WORK WM_APP + 0x100
#define WM_FINISH WM_APP + 0x101
value_map *vThreadsIdles;
//---------------------------------------------------------------------------
#pragma argsused
DWORD WINAPI ThreadMain(LPVOID p);
DWORD WINAPI ThreadWork(LPVOID p);
HANDLE hMutex;
int main(int argc, char* argv[])
{
value_map mThreads;
HANDLE handle;
DWORD dw;
hMutex = CreateMutex(NULL,false,"Sample");
for (int iThreadIndex = 0; iThreadIndex < 10; ++iThreadIndex)
{
handle = CreateThread(NULL,0,ThreadWork,NULL,0,&dw);
mThreads.insert(valType(iThreadIndex,dw));
}
//主线程;
handle = CreateThread(NULL,0,ThreadMain,(LPVOID)&mThreads,0,&dw);
WaitForSingleObject(handle,INFINITE);
CloseHandle(handle);
CloseHandle(hMutex);
return 0;
}
//---------------------------------------------------------------------------
DWORD WINAPI ThreadMain(LPVOID p)
{
TDateTime dtNow;
vThreadsIdles = (value_map *)p;
int iSecond;
MSG msg;
int iRet;
bool blPostTM;
value_map::iterator iter;
cout << "Start" << endl;
DWORD dThread;
int iID;
while(true)
{
dtNow = Date().CurrentDateTime();
//当前时间秒数小于30时执行
if(dtNow.FormatString("ss").ToInt() < 30)
{
iSecond = 1000;
//得到可用处理线程
try
{
WaitForSingleObject(hMutex,INFINITE);
if( 0 == vThreadsIdles->size())
{
continue;
}
//MAP中是后进先出
iter = vThreadsIdles->end();
--iter;
dThread = (*iter).second;
iID = (*iter).first;
vThreadsIdles->erase(iID);
}
__finally
{
ReleaseMutex(hMutex);
}
//投递消息
while(!(blPostTM = PostThreadMessage(dThread,WM_WORK,iID,0)))
{
//投递超时条件
if(iSecond == 3000)
{
break;
}
Sleep(iSecond);
iSecond += 1000;
}
if(!blPostTM)
{
//投递失败线程重回空闲池
WaitForSingleObject(hMutex,INFINITE);
vThreadsIdles->insert(valType(iID,dThread));
ReleaseMutex(hMutex);
cout << AnsiString(dThread).c_str() << "消息投递失败" << endl;
continue;
}
cout << AnsiString(dThread).c_str() << "消息投递成功" << endl;
}
}
}
DWORD WINAPI ThreadWork(LPVOID p)
{
MSG msg;
int iRet;
int iSecond;
bool blPostTM;
while(true)
{
iRet = GetMessage(&msg,NULL,0,0);
if(WM_WORK == msg.message)
{
cout << AnsiString(GetCurrentThreadId()).c_str() << "正在处理...." << endl;
Sleep(5000);
//处理完成线程重回空闲池
WaitForSingleObject(hMutex,INFINITE);
vThreadsIdles->insert(valType(msg.wParam,GetCurrentThreadId()));
ReleaseMutex(hMutex);
cout << AnsiString(GetCurrentThreadId()).c_str() << "空闲" << endl;
}
}
}