函数指针和多线程事例

/*
 输出:
 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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值