线程池中的任务队列:
线程池,是由一个任务队列和一组处理队列的线程组成。一但工作进程需要处理某个可能“阻塞”的操作,不用自己操作,将其作为一个任务放到线程的队列,接着会被某个空闲线程提取处理。
#include <iostream>
#define MAX_SIZE 50
using namespace std;
typedef struct _QNode
{
int id;
void (*handler)(void);
struct _QNode* next;
}QNode;
typedef QNode* QueuePtr;
typedef struct Queue
{
int length;
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//分配线程执行的任务结点
QueuePtr thread_task_alloc()
{
QNode* task;
task = (QNode*)calloc(1, sizeof(QNode));
if (task==NULL)
{
return NULL;
}
return task;
}
//队列初始化,将队列初始化为空队列
void initQueue(LinkQueue* LQ)
{
if (!LQ) return;
LQ->front = LQ->rear = NULL;
LQ->length = 0;
}
//判断队列是否为满
int isFull(LinkQueue* LQ)
{
if (!LQ) return 0;
if (LQ->length==MAX_SIZE) return 1;
return 0;
}
//判断队列为空
int isEmpty(LinkQueue* LQ)
{
if (!LQ) return 0;
if (LQ->length == 0) return 1;
return 0;
}
//入队,只能从队尾入
//是否为满,是否为空(front)
int enterQueue(LinkQueue* LQ,QNode* node)
{
if (!LQ || !node) return 0;
if (isFull(LQ))
{
cout << "队列已满" << endl;
return 0;
}
node->next = NULL;
if (isEmpty(LQ))
{
LQ->front = LQ->rear = node;
}
else
{
LQ->rear->next = node;
LQ->rear = node;
}
LQ->length++;
return 1;
}
//出队,只能从头出
QNode* PopQueue(LinkQueue* LQ)
{
if (!LQ || isEmpty(LQ)) {
cout << "队列为空" << endl;
return 0;
}
QueuePtr tmp = NULL;
tmp = LQ->front;
LQ->front = tmp->next;
if (!LQ->front) LQ->rear = NULL;
LQ->length--;
return tmp;
}
//打印
void printQueue(LinkQueue* LQ)
{
if (!LQ) return ;
QueuePtr tmp;
tmp = LQ->front;
while (tmp)
{
cout <<tmp->id <<"\t";
tmp = tmp->next;
}
cout << endl;
}
//清空队列
void clearQueue(LinkQueue* LQ)
{
if (!LQ) return;
while (LQ->front)
{
QueuePtr tmp = LQ->front;
LQ->front = tmp->next;
delete tmp;
}
LQ->front = LQ->rear = NULL;
LQ->length = 0;
}
int getLength(LinkQueue* LQ)
{
if (!LQ) return 0;
return LQ->length;
}
//任务1
void task1()
{
cout << "看代码" << endl;
}
//任务2
void task2()
{
cout << "写代码" << endl;
}
int main()
{
LinkQueue* LQ = new LinkQueue;
QueuePtr task = NULL;
initQueue(LQ);
//任务1入队
task = thread_task_alloc();
task->id = 1;
task->handler = &task1;
enterQueue(LQ, task);
cout << "任务1入队" << endl;
//任务2入队
task = thread_task_alloc();
task->id = 2;
task->handler = &task2;
enterQueue(LQ, task);
cout << "任务2入队" << endl;
//打印任务队列中的元素
cout << "队列中的元素(总共" << getLength(LQ) << "个):";
printQueue(LQ);
cout << endl;
//出队,执行任务
cout << "开始执行任务队列。。。" << endl << endl;
while (task=PopQueue(LQ))
{
task->handler();
delete task;
}
cout << endl << "任务结束" << endl;
delete LQ;
system("pause");
return 0;
}