利用队列操作,模拟实现打印作业任务管理,本次使用队列的操作会使用到C++自带的队列库,首先打印机的是一个临界资源,对打印机的访问时互斥的,每次只允许一个作业进行打印,不能并发执行,其次针对打印的PV操作一定成对存在,否则会出现死锁现象。
运行效果如图:
#include<stdio.h>
#include<iostream>
#include "Windows.h"
#include<queue>
#include<string>
using namespace std;
int my_exit = 0;//设置线程退出标识符
CRITICAL_SECTION my_printer; //创建临界区对象
typedef int QElemType;
#define MAXSIZE 3 //定义等待队列的最大数目
//定义一个结构体可以同时存储作业序号和打印内容
typedef struct {
int num; //作业序号
string str;//打印内容
}work;
queue<work> printer_work, waiting_work;//定义两个队列分别是等待队列以及打印队列
//添加作业
DWORD CALLBACK addHomework(LPVOID param)
{
while (my_exit) {
EnterCriticalSection(&my_printer); //进入打印队列
{
work tmp, t;
cout << "\n/*-*-*-*-*-*-*-*-*请输入你要打印的作业数量...(输入 -1退出打印)*-*-*-*-*-*-*-*-*/\n";
int num;
cin >> num;
if (num == -1) {
LeaveCriticalSection(&my_printer);
while (!waiting_work.empty()) //阻塞当前线程并清空队列
Sleep(0);
my_exit = 0;//设置标志位
break;
}
for (int i = 0; i < num; i++) {
cout << "\n\n/*-*-*-*-*-*-*-*-*请输入内容:*-*-*-*-*-*-*-*-*/\n";
cin >> tmp.str;
tmp.num = i;
//如果队未满
if (printer_work.size() <= MAXSIZE) {
LeaveCriticalSection(&my_printer);//退出临界资源
while (printer_work.size() == MAXSIZE)
Sleep(0);
EnterCriticalSection(&my_printer);//访问临界资源
waiting_work.push(tmp);//入队
printer_work.push(tmp);//入队
}
t = waiting_work.front();//获取队头元素值
cout << "/*-*-*-*-*-*-*-*-*作业" << t.num << "进入打印等待队列,请稍等......*-*-*-*-*-*-*-*-*/";
waiting_work.pop();
}
}
LeaveCriticalSection(&my_printer);
}
return 0;
}
DWORD CALLBACK printHomework(LPVOID param)
{
while (my_exit) {
EnterCriticalSection(&my_printer); //进入打印队列
{
while (!printer_work.empty()) {
work hw;
hw = printer_work.front();
printer_work.pop();//出队,等待队列的作业数少1
cout << "\n/*-*-*-*-*-*-*-*-*作业 " << hw.num << "正在被打印 ,请稍等......*-*-*-*-*-*-*-*-*/\n";
cout << "/*-*-*-*-*-*-*-*-*内容为:" << hw.str << "*-*-*-*-*-*-*-*-*/\n";
cout << endl;
}
}
LeaveCriticalSection(&my_printer);
while (printer_work.empty())
Sleep(0);
}
return 0;
}
int main(int argc, char const* argv[])
{
InitializeCriticalSection(&my_printer);
DWORD threadId_1;//线程1
DWORD threadId_2;
HANDLE hThread_1;
HANDLE hThread_2;
my_exit = 1;
cout << "\n\n/---------------------------*打印机开启中......*---------------------------/\n\n";
//
hThread_1 = CreateThread(NULL, 0, addHomework, NULL, 0, &threadId_1);
if (hThread_1 == NULL) {
printf("线程1创建失败!\n");
exit(1);
}
hThread_2 = CreateThread(NULL, 0, printHomework, NULL, 0, &threadId_2);
if (hThread_2 == NULL) {
printf("线程2创建失败!\n");
exit(1);
}
while (my_exit)
Sleep(0);
system("pause");
cout << "\n\n/---------------------------*正在关闭打印机......*---------------------------/\n\n";
DeleteCriticalSection(&my_printer);//删除临界资源
return 0;
}