// T25.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//VS2019编译通过并可运行
#include <vector>
#include <queue>
#include <thread>
#include <iostream>
#include <stdexcept>
#include <condition_variable>
#include <memory>
#include<string>
const int MAX_THREADS = 10; //最大线程数目设定为n=10
template <typename T>
class threadPool
{
public:
threadPool(int number = 1);
~threadPool();
bool append(T* request);//向请求队列<task_queue>中添加任务<T *>
private:
static void* worker(void* s);
void run();//从任务队列中取出并执行
private:
std::vector<std::thread> work_threads; //工作线程
std::queue<T*> tasks_queue; //任务队列
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
template <typename T>
threadPool<T>::threadPool(int number) : stop(false)
{
if (number <= 0 || number > MAX_THREADS)
throw std::exception();
for (int i = 0; i < number; i++)
{
std::cout << "创建第" << i << "个线程 " << std::endl;
work_threads.emplace_back(worker, this);
}
}
template <typename T>
inline threadPool<T>::~threadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (auto& i : work_threads)
i.join();
}
template <typename T>
bool threadPool<T>::append(T * request)
{
queue_mutex.lock();//由于工作队列被所有线程共享,操作时需要加锁
tasks_queue.push(request);
queue_mutex.unlock();
condition.notify_one(); //线程池添加进去了任务,要通知等待的线程
return true;
}
template <typename T>
void* threadPool<T>::worker(void* s)
{
threadPool* pool = (threadPool*)s;
pool->run();
return pool;
}
template <typename T>
void threadPool<T>::run()
{
while (!stop)
{
std::unique_lock<std::mutex> lk(this->queue_mutex);
this->condition.wait(lk, [this] { return !this->tasks_queue.empty(); });
if (this->tasks_queue.empty())//如果任务队列不为空,需要停止等待唤醒
{
continue;
}
else
{
T* request = tasks_queue.front();
tasks_queue.pop();
if (request)
request->process();
}
}
}
using namespace std;
class Task
{
public:
void process()
{
//cout << "running..." << endl;
}
};
int main(void)
{
threadPool<Task> pool(9);
std::string str;
while (1)
{
Task* task = new Task();//使用智能指针
pool.append(task);
delete task;
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
吉林大学软件学院卓班设计模式第一次作业
共10个文件
cpp:9个
docx:1个
需积分: 33 10 下载量 181 浏览量
2019-10-21
19:18:11
上传
评论 1
收藏 56KB RAR 举报
温馨提示
吉林大学软件学院卓班设计模式第一次作业 一. 使用分类稳定和变化的方法,重新设计类,使得新设计能以扩展代码的方式适应变化 未来可能会增加新的数据成员如mVal3, do1和do2中可能访问mVal1、mVal2、mVal3等 二. 按指定的要求或模式,给出实现。 1. 使用工厂方法模式实现工厂类。其中图书馆可能增加其他子类型,体育馆可可能增加具体子类。 2. 请用C++语言具体实现多线程中lazy式的单例模式(具体的锁机制,可任意)。 3. 若已知文科图书馆和理科图书馆各只有唯一一个,请参考课件中”多个单例类”,实现文科图书馆和理科图书馆的单例化。 4. 显然,一套场所组合对应一个工厂,请实现将各工厂也单例化。 5. 一个线程对象可以是多种状态(运行,空闲,挂起等),创建线程是非常耗资源的。线程池可以较好地避免频繁创建线程:一个线程池可以聚合N个线程(线程初始状态为空闲,N=10)。当客户申请线程时,从线程池中查找空闲的线程,找到后返回该线程;若没找到,返回异常。请用多例模式设计线程池类(ThreadPool)
资源推荐
资源详情
资源评论
收起资源包目录
作业01.rar (10个子文件)
作业01
作业01.docx 59KB
H23.cpp 933B
H13.cpp 597B
H11.cpp 625B
H24.cpp 2KB
H14.cpp 569B
H22.cpp 534B
H21.cpp 773B
H25.cpp 2KB
H12.cpp 694B
共 10 条
- 1
资源评论
啊哈0809
- 粉丝: 43
- 资源: 40
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功