不定个数的C++函数指针
不定个数的C++函数指针
关于多线程下利用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();
- }
评论暂时关闭