包括了如何创建一个线程, 等待线程结束, 向线程提供数据,使用mutex互锁,通知线程结束.
typedef struct{ int mWidth; int mHeight; int mCount; vector
class AutoLock{public: HANDLE mMutex; AutoLock(HANDLE mutex) { mMutex = mutex; WaitForSingleObject(mutex, INFINITE ); } ~AutoLock() { ReleaseMutex(mMutex); }};
class ImpFindTargetMsmMgr{public: HANDLE mutex; ImpFindTargetMsmMgr() { mQuit = false; mutex = CreateMutex( NULL, FALSE, NULL ); } ~ImpFindTargetMsmMgr() { CloseHandle(mutex); } queue<_finddata> mQueue; void Add(_FINDDATA d) {
AutoLock a(mutex); mQueue.push(d);
} void Remove() { AutoLock a(mutex); mQueue.pop(); } _FINDDATA& Head() { return mQueue.front(); }
void clear() { AutoLock a(mutex); while(mQueue.size()) mQueue.pop(); } bool mQuit;};
class ThreadBaseClass{public: static DWORD WINAPI ThreadFunc(void *aObj) { ThreadBaseClass *obj = (ThreadBaseClass *)aObj; return obj->ThreadEntry(); }
HANDLE Run() { ThreadHandle = CreateThread(0, 0, ThreadFunc, (void *)this, 0, &ThreadId); return ThreadHandle; }
virtual DWORD ThreadEntry() = 0;
void Join(){ WaitForSingleObject(ThreadHandle, INFINITE ); } DWORD ThreadId; HANDLE ThreadHandle;};class ThreadOneClass : public ThreadBaseClass
{public: ImpFindTargetMsmMgr* mData; ThreadOneClass(LPVOID p) { mData = (ImpFindTargetMsmMgr*)p; } DWORD ThreadEntry();};
DWORD ThreadOneClass::ThreadEntry(){ ImpFindTargetMsmMgr& mgr = mData; vector
while (1) { if (mgr.mQueue.size() ) { _FINDDATA& data = mgr.Head(); FindAllTargets(data.mSnapshot, data.mWidth , data.mHeight , data.mCount);
data.mSnapshot.clear(); mgr.Remove(); } else { if (mgr.mQuit) break; Sleep(300); } } return 1;}
DWORD FindImage(){ ImpFindTargetMsmMgr mgr ;
ThreadOneClass helper(&mgr); helper.Run();
//Sample Test Code here for (int i = 0; ihelper.Join(); return 1;}