码迷,mamicode.com
首页 > 编程语言 > 详细

一个简单线程池例子

时间:2016-05-12 17:01:18      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

// Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <vector>

typedef unsigned (__stdcall*LP_THREAD_FUN)(void*);

class Thread{
public:
	Thread(){
		m_fun = NULL;
		m_param = NULL;
		m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, this, CREATE_SUSPENDED, NULL);
		printf("Thread Create: %08X\n", m_hThread);
	}
	~Thread(){
		Terminate();
		CloseHandle(m_hThread);
	}

	void SetThreadFun(LP_THREAD_FUN fun, void* param){
		m_fun = fun;
		m_param = param;
	}
	void Start(){
		DWORD dwCount = ResumeThread(m_hThread);
		if (dwCount == -1){
			printf("ResumeThread Fail, LastError: %d", GetLastError());
		}
	}
	void Pause(){
		DWORD dwCount = SuspendThread(m_hThread);
		if (dwCount == -1){
			printf("SuspendThread Fail, LastError: %d", GetLastError());
		}
	}
	void Resume(){
		DWORD dwCount = ResumeThread(m_hThread);
		if (dwCount == -1){
			printf("ResumeThread Fail, LastError: %d", GetLastError());
		}
	}
	void Terminate(){
		if (!TerminateThread(m_hThread, 0)){
			printf("TerminateThread Fail, LastError: %d", GetLastError());
		}
	}
protected:
	static unsigned __stdcall ThreadFun(void* param){
		Thread* p = (Thread*)param;
		if (p && p->m_fun)
		{
			p->m_fun(p->m_param);
		}
		return 0;
	}
	HANDLE m_hThread;
	LP_THREAD_FUN m_fun;
	void* m_param;
};

class ThreadPool{
public:
	ThreadPool(): m_iAvailableIndex(0){}
	~ThreadPool(){
		std::vector<Thread*>::iterator ita = m_vecThread.begin();
		while (ita != m_vecThread.end()){
			delete (Thread*)(*ita);
			ita++;
		}
		m_vecThread.clear();
	}

	void Init(int threadcount){
		m_vecThread.resize(threadcount);
		for (int i = 0; i < threadcount; ++i){
			m_vecThread[i] = new Thread;
		}
	}

	Thread* GetAvailabelThread(){
		if (m_iAvailableIndex < m_vecThread.size()){
			return m_vecThread[m_iAvailableIndex++];
		}
		return NULL;
	}

protected:
	std::vector<Thread*> m_vecThread;
	int m_iAvailableIndex;
};

unsigned __stdcall TestFun(void* p)
{
	printf("TestFun: %d", p);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	ThreadPool pool;
	int count = 0;
	printf("Please input thread count: ");
	scanf("%d", &count);
	pool.Init(count);

	Thread* p = pool.GetAvailabelThread();
	if (p)
	{
		printf("Please input scedule thread: ");
		scanf("%d", &count);
		p->SetThreadFun(TestFun, (void*)count);
		printf("Run thread: ");
		scanf("%d", &count);
		p->Start();
	}

	system("@pause");
	return 0;
}

一个简单线程池例子

标签:

原文地址:http://blog.csdn.net/u012532305/article/details/51361379

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!