歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 不定個數的C++函數指針

不定個數的C++函數指針

日期:2017/3/1 10:06:44   编辑:Linux編程

關於多線程下利用vector保存函數指針並調用的方法,這是一個最簡單的函數指針調用實例,大家可以看到這樣對於處理一些第一時間處理數據的業務非常合適,這樣處理的實時性非常好,當然而且可以多個處理函數來處理數據,也可以將mytest這個class 封裝起來,是外部使用的人不必關心內部如何產生數據的。外部直接

  1. struct mystuct
  2. {
  3. int myInt;
  4. char myStr[100];
  5. };
  6. class mytest
  7. {
  8. private:
  9. static unsigned long WINAPI TestThread(LPVOID lpvoid);
  10. volatile unsigned long threadRun;
  11. int CreateTestThread();
  12. vector<void (*)(mystuct *pdata)> functionvector;
  13. HANDLE m_ExitEvent;
  14. public:
  15. mytest(void){}
  16. ~mytest(void){}
  17. int AddFunctionAddr(void (*_ProcesseFunction)(mystuct *pdata));
  18. void initialize();
  19. void shutdown();
  20. };
  21. void mytest::initialize()
  22. {
  23. CreateTestThread();
  24. }
  25. void mytest::shutdown()
  26. {
  27. InterlockedExchange(&threadRun,0);
  28. WaitForSingleObject(m_ExitEvent,INFINITE);
  29. ResetEvent(m_ExitEvent);
  30. CloseHandle(m_ExitEvent);
  31. }
  32. int mytest::AddFunctionAddr(void (*_ProcesseFunction)(mystuct *pdata))
  33. {
  34. functionvector.push_back(_ProcesseFunction);
  35. return 0;
  36. }
  37. unsigned long WINAPI mytest::TestThread(LPVOID lpvoid)
  38. {
  39. mytest* pMytest = (mytest*)lpvoid;
  40. int i =15;
  41. while(1)
  42. {
  43. mystuct _mystuct;
  44. memset(_mystuct.myStr,0,100);
  45. memcpy(_mystuct.myStr,"月·小軒",sizeof("月·小軒"));
  46. _mystuct.myInt=i;
  47. if (0==pMytest->threadRun)
  48. {
  49. break;
  50. }
  51. for (int i=0;i<(int)(pMytest->functionvector.size());i++)
  52. {
  53. if (NULL!=(pMytest->functionvector[i]))
  54. {
  55. (*(pMytest->functionvector[i]))(&_mystuct);
  56. }
  57. }
  58. i++;
  59. Sleep(1000);
  60. }
  61. SetEvent(pMytest->m_ExitEvent);
  62. return 0;
  63. }
  64. int mytest::CreateTestThread()
  65. {
  66. m_ExitEvent= CreateEvent(NULL,TRUE,FALSE,L"test_Eixt");
  67. InterlockedExchange(&threadRun,1);
  68. DWORD dwthreadID;
  69. HANDLE h_Handle= CreateThread(NULL,NULL,TestThread,this,0,&dwthreadID);
  70. if (NULL==h_Handle)
  71. {
  72. CloseHandle(h_Handle);
  73. return 1;
  74. }
  75. CloseHandle(h_Handle);
  76. return 0;
  77. }
  78. void printFunction1(mystuct* data)
  79. {
  80. int resultNumber = data->myInt;
  81. printf("%d\t",resultNumber);
  82. }
  83. void printFunction2(mystuct* data)
  84. {
  85. printf("%s\t",data->myStr);
  86. }
  87. void main()
  88. {
  89. mytest* _mytest = new mytest();
  90. _mytest->AddFunctionAddr(printFunction1);
  91. _mytest->AddFunctionAddr(printFunction2);
  92. _mytest->initialize();
  93. system("pause");
  94. _mytest->shutdown();
  95. }
Copyright © Linux教程網 All Rights Reserved