/*
输出:
printFunction1:
0
printFunction2:
我的博客:http://blog.csdn.net/windows_nt
printFunction1:
1
printFunction2:
我的博客:http://blog.csdn.net/windows_nt
printFunction1:
2
printFunction2:
我的博客:http://blog.csdn.net/windows_nt
printFunction1:
*/
#include <wtypes.h>
#include <iostream>
#include <vector>
#include <atlstr.h>
using namespace std;
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((volatile LONG *)&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 = 0;
while(1)
{
mystuct _mystuct;
memset(_mystuct.myStr, 0, 100);
memcpy(_mystuct.myStr, "我的博客:http://blog.csdn.net/windows_nt", sizeof("我的博客:http://blog.csdn.net/windows_nt"));
_mystuct.myInt = i;
if (0 == pMytest->threadRun)
{
break;
}
for (int j = 0; j < (int)(pMytest->functionvector.size()); j++)
{
if (NULL != (pMytest->functionvector[j]))
{
(*(pMytest->functionvector[j]))(&_mystuct);
}
}
i++;
Sleep(1000);
}
SetEvent(pMytest->m_ExitEvent);
return 0;
}
int mytest::CreateTestThread()
{
m_ExitEvent= CreateEvent(NULL, TRUE, FALSE, CString("test_Eixt"));
InterlockedExchange((volatile LONG *)&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)
{
printf("printFunction1:\n");
int resultNumber = data->myInt;
printf("%d\n", resultNumber);
}
void printFunction2(mystuct* data)
{
printf("printFunction2:\n");
printf("%s\n", data->myStr);
}
void main()
{
mytest* _mytest = new mytest();
_mytest->AddFunctionAddr(printFunction1);
_mytest->AddFunctionAddr(printFunction2);
_mytest->initialize();
getchar(); //主进程挂起,调用system("pause");亦可
_mytest->shutdown();
}
函数指针和多线程事例
最新推荐文章于 2023-06-09 20:24:21 发布