正文

C++多線程編程的示範程序

(2008-05-01 22:49:38) 下一個
包括了如何創建一個線程, 等待線程結束, 向線程提供數據,使用mutex互鎖,通知線程結束.
typedef struct{ int mWidth; int mHeight; int mCount; vector mSnapshot;}_FINDDATA;
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 FindAllTargets(vector& snapshot, int width, int height, int count);
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; i< 2; i++) { _FINDDATA data; data.mCount= i; data.mHeight = 10; data.mWidth = 10; data.mSnapshot.resize(100, i); mgr.Add(data); } mgr.mQuit = true;
helper.Join(); return 1;}
[ 打印 ]
閱讀 ()評論 (0)
評論
目前還沒有任何評論
登錄後才可評論.