当前位置: 首页 > news >正文

做系统下载网站建设seo长沙

做系统下载网站建设,seo长沙,一般网站图标是用什么做的,吉林沈阳网站建设文章目录 九、多线程10. 线程池 未完待续 九、多线程 10. 线程池 这里我没实现一些 懒汉单例模式 的线程池,并且包含 日志打印 的线程池: Makefile: threadpool:Main.ccg -o $ $^ -stdc11 -lpthread .PHONY:clean clean:rm -f threadpoolT…

文章目录

  • 九、多线程
    • 10. 线程池
  • 未完待续


九、多线程

10. 线程池

这里我没实现一些 懒汉单例模式 的线程池,并且包含 日志打印 的线程池:
Makefile

threadpool:Main.ccg++ -o $@ $^ -std=c++11 -lpthread
.PHONY:clean
clean:rm -f threadpool

Thread.hpp

#ifndef __THREAD_HPP__
#define __THREAD_HPP__#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <pthread.h>namespace ThreadModule
{// 类型别名using func_t = std::function<void(std::string)>;// 线程类class Thread{public:void Excute(){_func(_threadname);}public:Thread(func_t func, std::string name = "none-name"):_func(func),_threadname(name),_stop(true){}// 执行任务static void *threadroutine(void *args){Thread *self = static_cast<Thread*>(args);self->Excute();return nullptr;}// 启动线程bool Start(){int n = pthread_create(&_tid, nullptr, threadroutine, this);if(!n){_stop = false;return true;}else{return false;}}// 停止线程void Detach(){if(!_stop){pthread_detach(_tid);}}// 等待线程结束void Join(){if(!_stop){pthread_join(_tid, nullptr);}}std::string name(){return _threadname;}void Stop(){_stop = true;}~Thread(){}private:pthread_t _tid;std::string _threadname;func_t _func;bool _stop;};
}#endif

LockGuard.hpp

#ifndef __LOCK_GUARD_HPP__
#define __LOCK_GUARD_HPP__#include <iostream>
#include <pthread.h>class LockGuard
{
public:// 构造函数加锁LockGuard(pthread_mutex_t *mutex):_mutex(mutex){pthread_mutex_lock(_mutex);}// 析构函数解锁~LockGuard(){pthread_mutex_unlock(_mutex);}
private:pthread_mutex_t *_mutex;
};#endif

Log.hpp

#pragma once#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
#include <ctime>
#include <cstdarg>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include "LockGuard.hpp"// 宏定义,用于定义日志格式
#define LOG(level, format, ...) do{LogMessage(__FILE__, __LINE__, gIsSave, level, format, ##__VA_ARGS__);}while (0)
// 将日志输入到文件
#define EnableFile() do{gIsSave = true;}while (0)
// 将日志输出到显示器
#define EnableScreen() do{gIsSave = false;}while (0)bool gIsSave = false;
// 日志文件名
const std::string logname = "log.txt";// 枚举日志级别
enum Level
{DEBUG = 0,INFO,WARNING,ERROR,FATAL
};// 保存日志到文件
void SaveFile(const std::string &filename, const std::string &message)
{std::ofstream out(filename, std::ios::app);if (!out.is_open()){return;}out << message;out.close();
}// 日志级别转字符串
std::string LevelToString(int level)
{switch (level){case DEBUG:return "Debug";case INFO:return "Info";case WARNING:return "Warning";case ERROR:return "Error";case FATAL:return "Fatal";default:return "Unknown";}
}// 获取当前时间字符串
std::string GetTimeString()
{time_t curr_time = time(nullptr);struct tm *format_time = localtime(&curr_time);if (format_time == nullptr)return "None";char time_buffer[1024];snprintf(time_buffer, sizeof(time_buffer), "%d-%d-%d %d:%d:%d",format_time->tm_year + 1900,format_time->tm_mon + 1,format_time->tm_mday,format_time->tm_hour,format_time->tm_min,format_time->tm_sec);return time_buffer;
}// 日志锁,同一时刻只能写一个日志
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;// 日志信息
void LogMessage(std::string filename, int line, bool issave, int level, const char *format, ...)
{// 日志级别std::string levelstr = LevelToString(level);// 时间std::string timestr = GetTimeString();// 进程idpid_t selfid = getpid();// 日志内容char buffer[1024];va_list arg;va_start(arg, format);vsnprintf(buffer, sizeof(buffer), format, arg);va_end(arg);// 日志格式化std::string message = "[" + timestr + "]" + "[" + levelstr + "]" +"[" + std::to_string(selfid) + "]" +"[" + filename + "]" + "[" + std::to_string(line) + "] " + buffer + "\n";LockGuard lockguard(&lock);// 输出日志if (!issave){std::cout << message;}else{SaveFile(logname, message);}
}

Task.hpp

#pragma once#include <iostream>
#include <string>
#include <functional>class Task
{
public:Task(){}Task(int a, int b):_a(a),_b(b),_result(0){}// 执行加法功能void Excute(){_result = _a + _b;}// 结果std::string ResultToString(){return std::to_string(_a) + "+" + std::to_string(_b) + "=" + std::to_string(_result);}// 问题std::string DebugToString(){return std::to_string(_a) + "+" + std::to_string(_b) + "= ?";}// 重载()运算符void operator()(){Excute();}
private:int _a;int _b;int _result;
};

ThreadPool.hpp

#pragma once#include <iostream>
#include <vector>
#include <queue>
#include <pthread.h>
#include "Log.hpp"
#include "Thread.hpp"
#include "LockGuard.hpp"using namespace ThreadModule;// 线程池默认线程数
const static int gdefaultthreadnum = 10;template <typename T>
class ThreadPool
{
private:// 线程互斥锁void LockQueue(){pthread_mutex_lock(&_mutex);}// 线程互斥解锁void UnlockQueue(){pthread_mutex_unlock(&_mutex);}// 线程等待void ThreadSleep(){pthread_cond_wait(&_cond, &_mutex);}// 线程唤醒void ThreadWakeup(){pthread_cond_signal(&_cond);}// 唤醒全部线程void ThreadWakeupAll(){pthread_cond_broadcast(&_cond);}// 私有构造函数ThreadPool(int threadnum = gdefaultthreadnum):_threadnum(threadnum),_waitnum(0),_isrunning(false){// 初始化锁pthread_mutex_init(&_mutex, nullptr);pthread_cond_init(&_cond, nullptr);// 日志LOG(INFO, "ThreadPool Construct()");}// 初始化线程池void InitThreadPool(){// 创建一批线程for (int num = 0; num < _threadnum; num++){std::string name = "thread-" + std::to_string(num + 1);_threads.emplace_back(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1), name);// 日志LOG(INFO, "init thread %s done", name.c_str());}_isrunning = true;}// 启动线程池void Start(){for (auto &thread : _threads){thread.Start();}}// 任务处理函数void HandlerTask(std::string name) // 类的成员方法,也可以成为另一个类的回调方法,方便我们继续类级别的互相调用!{// 日志LOG(INFO, "%s is running...", name.c_str());while (true){// 加锁LockQueue();while (_task_queue.empty() && _isrunning){_waitnum++;ThreadSleep();_waitnum--;}// 退出情况if (_task_queue.empty() && !_isrunning){UnlockQueue();break;}// 取出任务T t = _task_queue.front();_task_queue.pop();UnlockQueue();// 日志LOG(DEBUG, "%s get a task", name.c_str());// 执行任务t();// 日志LOG(DEBUG, "%s handler a task, result is: %s", name.c_str(), t.ResultToString().c_str());}}// 禁用拷贝构造和赋值操作ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;ThreadPool(const ThreadPool<T> &) = delete;
public:static ThreadPool<T> *GetInstance(){// 首次使用时,创建线程池单例if (nullptr == _instance){// 对于多线程创建单例时加锁,保证线程安全LockGuard lockguard(&_lock);if (nullptr == _instance){// 创建线程池实例_instance = new ThreadPool<T>();_instance->InitThreadPool();_instance->Start();LOG(DEBUG, "创建线程池单例");return _instance;}}// 已经创建过线程池单例,直接返回LOG(DEBUG, "获取线程池单例");return _instance;}// 停止线程池void Stop(){LockQueue();_isrunning = false;ThreadWakeupAll();UnlockQueue();}// 等待线程池退出void Wait(){for (auto &thread : _threads){thread.Join();LOG(INFO, "%s is quit...", thread.name().c_str());}}// 向线程池中添加任务bool Enqueue(const T &t){bool ret = false;LockQueue();if (_isrunning){_task_queue.push(t);if (_waitnum > 0){ThreadWakeup();}LOG(DEBUG, "enqueue task success");ret = true;}UnlockQueue();return ret;}// 析构自动释放锁资源~ThreadPool(){pthread_mutex_destroy(&_mutex);pthread_cond_destroy(&_cond);}
private:// 线程池中线程个数int _threadnum;// 线程std::vector<Thread> _threads;// 任务队列std::queue<T> _task_queue;// 互斥锁pthread_mutex_t _mutex;// 条件变量pthread_cond_t _cond;// 等待线程数int _waitnum;// 线程池是否运行bool _isrunning;// 线程池单例static ThreadPool<T> *_instance;// 全局锁static pthread_mutex_t _lock;
};// 初始化静态变量
template <typename T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;// 全局锁
template <typename T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;

Main.cc

#include "ThreadPool.hpp"
#include "Task.hpp"
#include "Log.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <ctime>int main()
{// 日志LOG(DEBUG, "程序已经加载");sleep(2);// 创建线程池单例ThreadPool<Task>::GetInstance();sleep(2);// 获取单例ThreadPool<Task>::GetInstance();sleep(2);ThreadPool<Task>::GetInstance();sleep(2);ThreadPool<Task>::GetInstance();sleep(2);// 等待线程结束ThreadPool<Task>::GetInstance()->Wait();sleep(2);return 0;
}

结果演示:
在这里插入图片描述


未完待续


文章转载自:
http://dinncojeopardous.bpmz.cn
http://dinncoditcher.bpmz.cn
http://dinncodefier.bpmz.cn
http://dinncopyrethroid.bpmz.cn
http://dinncoanabasis.bpmz.cn
http://dinncoclerestory.bpmz.cn
http://dinncodidact.bpmz.cn
http://dinncononresidential.bpmz.cn
http://dinncoknowledgable.bpmz.cn
http://dinncohemstitch.bpmz.cn
http://dinncooscule.bpmz.cn
http://dinncoope.bpmz.cn
http://dinncosestet.bpmz.cn
http://dinncomcluhanize.bpmz.cn
http://dinncoendow.bpmz.cn
http://dinncoenchanting.bpmz.cn
http://dinncostonechat.bpmz.cn
http://dinncohonshu.bpmz.cn
http://dinncohypergeusesthesia.bpmz.cn
http://dinncogalliwasp.bpmz.cn
http://dinncoscalarly.bpmz.cn
http://dinncoflorence.bpmz.cn
http://dinncooao.bpmz.cn
http://dinncocopse.bpmz.cn
http://dinncoworrywart.bpmz.cn
http://dinncoradiocompass.bpmz.cn
http://dinncodrambuie.bpmz.cn
http://dinncohelicograph.bpmz.cn
http://dinncophonasthenia.bpmz.cn
http://dinncojury.bpmz.cn
http://dinncoscattergun.bpmz.cn
http://dinncoliterality.bpmz.cn
http://dinncosymphysis.bpmz.cn
http://dinncolouisianian.bpmz.cn
http://dinncoschoolroom.bpmz.cn
http://dinncotroopial.bpmz.cn
http://dinncobootable.bpmz.cn
http://dinncotroublesomely.bpmz.cn
http://dinncosnatchy.bpmz.cn
http://dinncodefector.bpmz.cn
http://dinncodoxastic.bpmz.cn
http://dinncomultichannel.bpmz.cn
http://dinncopuritanical.bpmz.cn
http://dinncotangleberry.bpmz.cn
http://dinncokhurta.bpmz.cn
http://dinnconornicotine.bpmz.cn
http://dinncospinstry.bpmz.cn
http://dinncoprosodial.bpmz.cn
http://dinncooenophile.bpmz.cn
http://dinncoperugia.bpmz.cn
http://dinncorectification.bpmz.cn
http://dinncowien.bpmz.cn
http://dinncosalpingectomy.bpmz.cn
http://dinncocylindric.bpmz.cn
http://dinncoteleutospore.bpmz.cn
http://dinncolangsyne.bpmz.cn
http://dinncocorrody.bpmz.cn
http://dinncolevelly.bpmz.cn
http://dinncomonopropellant.bpmz.cn
http://dinncothermotolerant.bpmz.cn
http://dinncochiromegaly.bpmz.cn
http://dinncotangibility.bpmz.cn
http://dinncorecumbent.bpmz.cn
http://dinncofourflusher.bpmz.cn
http://dinncocytostome.bpmz.cn
http://dinncoteleconverter.bpmz.cn
http://dinncoimpeller.bpmz.cn
http://dinncosimsim.bpmz.cn
http://dinncoshark.bpmz.cn
http://dinncospanking.bpmz.cn
http://dinncorevest.bpmz.cn
http://dinncocloudling.bpmz.cn
http://dinnconitrous.bpmz.cn
http://dinncosinclair.bpmz.cn
http://dinncobacteriolysis.bpmz.cn
http://dinncoassistance.bpmz.cn
http://dinncostir.bpmz.cn
http://dinncohyposcope.bpmz.cn
http://dinncovermiculite.bpmz.cn
http://dinncotuberose.bpmz.cn
http://dinncocowpox.bpmz.cn
http://dinncocaneware.bpmz.cn
http://dinncoalkoxy.bpmz.cn
http://dinncocapuche.bpmz.cn
http://dinncocalve.bpmz.cn
http://dinncocounterintelligence.bpmz.cn
http://dinncobeguiling.bpmz.cn
http://dinncochickenshit.bpmz.cn
http://dinncoexcommunicable.bpmz.cn
http://dinncobehind.bpmz.cn
http://dinncoblellum.bpmz.cn
http://dinncoinformatics.bpmz.cn
http://dinncodefenceless.bpmz.cn
http://dinncodichotomy.bpmz.cn
http://dinncoczechic.bpmz.cn
http://dinncojalor.bpmz.cn
http://dinncoadapted.bpmz.cn
http://dinncovocationally.bpmz.cn
http://dinncohemelytron.bpmz.cn
http://dinncomhg.bpmz.cn
http://www.dinnco.com/news/1861.html

相关文章:

  • 科技网站 石家庄武汉网络关键词排名
  • 公司网站建设找哪家百度官网认证免费
  • 怎么做淘宝返利网站磁力岛
  • 如何更改asp网站自定义产品顺序深圳市网络品牌推广
  • 家里电脑可以做网站服务器吗浙江疫情最新消息
  • wordpress 粉丝实时seo排名点击软件
  • 广州外贸网站建设开发什么是网络营销渠道
  • 地产网站建设专业搜索引擎seo技术公司
  • 电脑版和手机版网站怎么做新闻小学生摘抄
  • 网站建设 可行性优秀网站seo报价
  • 网站的流量是怎么回事惠州百度seo地址
  • 大气网站模板免费下载做网站设计哪里有
  • 福州建站模板个人免费网上注册公司
  • 什么身一什么网站建设手游推广加盟
  • 盘县网站建设本周国内重大新闻十条
  • 口碑好的聊城网站建设河南百度推广代理商
  • 网站建设 账务处理优化防疫政策
  • xamp wordpress超级推荐的关键词怎么优化
  • 别人买了域名做违法网站seo搜索引擎优化简历
  • 云南建设网站做任务赚佣金的平台
  • 哪个网站做室内效果图厉害seo优化报告
  • asp的网站汽油价格最新调整最新消息
  • 广安网站建设成都网站seo设计
  • 大连手机自适应网站建设报价十大场景营销案例
  • 动态的网站大概多少钱百度推广账户优化方案
  • 百度云搜索引擎网站外包网络推广
  • 黄石下陆区建设局网站惠州抖音seo策划
  • 360网站推广怎么做整站排名优化品牌
  • xx网站建设策划方案宁波seo软件
  • 有哪些做ae小动效的网站查企业信息查询平台