關於多線程下利用vector保存函數指針並調用的方法,這是一個最簡單的函數指針調用實例,大家可以看到這樣對於處理一些第一時間處理數據的業務非常合適,這樣處理的實時性非常好,當然而且可以多個處理函數來處理數據,也可以將mytest這個class 封裝起來,是外部使用的人不必關心內部如何產生數據的。外部直接
- struct mystuct
- {
- int myInt;
- char myStr[100];
- };
-
-
- class mytest
- {
- private:
- static unsigned long WINAPI TestThread(LPVOID lpvoid);
-
-
- volatile unsigned long threadRun;
- int CreateTestThread();
- vector<void (*)(mystuct *pdata)> functionvector;
- HANDLE m_ExitEvent;
- public:
- mytest(void){}
- ~mytest(void){}
- int AddFunctionAddr(void (*_ProcesseFunction)(mystuct *pdata));
- void initialize();
- void shutdown();
-
-
- };
-
-
- void mytest::initialize()
- {
- CreateTestThread();
- }
- void mytest::shutdown()
- {
- InterlockedExchange(&threadRun,0);
- WaitForSingleObject(m_ExitEvent,INFINITE);
- ResetEvent(m_ExitEvent);
- CloseHandle(m_ExitEvent);
- }
- int mytest::AddFunctionAddr(void (*_ProcesseFunction)(mystuct *pdata))
- {
- functionvector.push_back(_ProcesseFunction);
- return 0;
- }
-
-
- unsigned long WINAPI mytest::TestThread(LPVOID lpvoid)
- {
- mytest* pMytest = (mytest*)lpvoid;
- int i =15;
- while(1)
- {
- mystuct _mystuct;
- memset(_mystuct.myStr,0,100);
- memcpy(_mystuct.myStr,"月·小軒",sizeof("月·小軒"));
- _mystuct.myInt=i;
-
-
- if (0==pMytest->threadRun)
- {
- break;
- }
-
-
- for (int i=0;i<(int)(pMytest->functionvector.size());i++)
- {
- if (NULL!=(pMytest->functionvector[i]))
- {
- (*(pMytest->functionvector[i]))(&_mystuct);
- }
- }
- i++;
- Sleep(1000);
- }
- SetEvent(pMytest->m_ExitEvent);
- return 0;
- }
-
-
- int mytest::CreateTestThread()
- {
- m_ExitEvent= CreateEvent(NULL,TRUE,FALSE,L"test_Eixt");
- InterlockedExchange(&threadRun,1);
-
-
-
-
- DWORD dwthreadID;
- HANDLE h_Handle= CreateThread(NULL,NULL,TestThread,this,0,&dwthreadID);
- if (NULL==h_Handle)
- {
- CloseHandle(h_Handle);
- return 1;
- }
- CloseHandle(h_Handle);
- return 0;
- }
-
-
- void printFunction1(mystuct* data)
- {
- int resultNumber = data->myInt;
- printf("%d\t",resultNumber);
- }
- void printFunction2(mystuct* data)
- {
- printf("%s\t",data->myStr);
- }
-
-
- void main()
- {
- mytest* _mytest = new mytest();
- _mytest->AddFunctionAddr(printFunction1);
- _mytest->AddFunctionAddr(printFunction2);
- _mytest->initialize();
-
-
- system("pause");
- _mytest->shutdown();
- }