#include<stdio.h>
#include<pthread.h>
#include<string>
#include<iostream>
using namespace std;
static pthread_mutex_t m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER; /** 线程同步锁 */
static pthread_cond_t m_pthreadCond = PTHREAD_COND_INITIALIZER; /** 线程同步的条件变量 */
#define MAX_NUM_THREAD 50;
pthread_t pthread_id[MAX_NUM_THREAD] = {0};
Mutex_Guard mutex_guard(m_pthreadCond);
class Task
{
public:
Task(){}
virtual ~Task()
virtual int run() = 0;
};
class TaskSend:public Task
{
TaskSend(){}
~TaskSend(){}
int run();
};
int TaskSend::run()
{
const int n = 100;
int s = 0;
for (int i = 0;i < n; ++i)
}
class ThreadPool
{
public:
ThreadPool(){}
ThreadPool(int NumofThd){};
~ThreadPool(){};
static ThreadPool* GetInstace();
void InitThreadPool();
static void StartProcess();
void AddTask();
void Stop(){};
private:
int m_numThd;// num of thread;
static ThreadPool* m_instance;
//static Mutex_Guard mutex_guard; //因为回调函数StartProcess必须是static的,所以所有该函数要调用的成员变量也要是static
static vector<Task*> m_oVecTask;
};
cPP文件定义如下:
ThreadPool* ThreadPool::m_instance = NULL;
//静态成员变量要在类外面定义
pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALZER;
//Mutex_Guard ThreadPool::mutex_guard(thread_mutex);
vector<Task*> ThreadPool::m_oVecTask;
void ThreadPool::ThreadPool(int NumofThd)
{
m_numThd = NumofThd;
InitThreadPool();
}
ThreadPool* ThreadPool::Instace(n)
{
if (NULL == m_instance)
{
m_instance = new(std::nothrow) ThreadPool(n);
}
return m_instance;
}
void ThreadPool::InitThreadPool()
{
for(int i = 0; i < m_iThreadNum; i++)
{
pthread_create(&pthread_id[i], NULL, StartProcess, NULL);
}
return ;
}
void ThreadPool::StartProcess()
{
pthread_t tid = pthread_self();
while(1)
{
Mutex_Guard mutex_guard(m_pthreadCond);
if (0 == m_oVecTask.size())
{
pthread_cond_wait(&m_pthreadCond, &m_pthreadCond);
}
vector<Task*>::iterator itTask = m_oVecTask.begin();
}
return ;
}
void ThreadPool::AddTask(const Task& t)
{
Mutex_Guard mutex_guard(m_pthreadCond);
m_oVecTask.push_back(t);
pthread_cond_siganl(&m_pthreadCond);
}
int main()
{
//初始化线程池
(void)ThreadPool::Instace(20);
//应用如下:
ThreadPool::Instace()->StartProcess();
return 0;
}
class Mutex_Guard
{
public:
Mutex_Guard(){mutex = 0;}
Mutex_Guard(pthread_mutex_t& mutex_other)
{
mutex = mutex_other;
int val = 0;
val = pthread_mutex_lock(&mutex);/*lock the mutex*/
if(val != 0)
{
printf("lock error.");
}
}
~Mutex_Guard()
{
int val = 0;
val = pthread_mutex_unlock(&mutex);/*unlock the mutex*/
if(val != 0)
{
printf("lock error.");
}
}
private:
Mutex_Guard(){}
Mutex_Guard(const Mutex_Guard& t2){}
Mutex_Guard& operator =(const Mutex_Guard& t2){}
private:
pthread_mutex_t mutex;
};
static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALZER;
if(pthread_mutex_init(&mutex,NULL) != 0 )
{
printf("Init metux error.");
exit(1);
}
pthread_mutex_unlock(&mutex);/*unlock the mutex*/
val = pthread_mutex_lock(&mutex);/*lock the mutex*/
if(val != 0)
{
printf("lock error.");
}
线程池
最新推荐文章于 2025-03-15 16:39:01 发布