阻塞队列提升+线程池反思——c++线程库

✨阻塞队列+线程池——vstudio✨
线程池实现——Linux
小线程池实现
c++并发编程(书籍)

✨阻塞队列代码——管理任务
 ✨代码
  ✨Log.h
  ✨Task.h
  ✨BlockQueue.h
 成员变量一览
 ✨反思总结
✨线程池——管理线程
 ✨结构介绍
 ✨代码
  ✨ThreadPool.h
 ✨反思总结
✨简化线程池
 ✨C++代码——thread库实现
 ✨C代码——pthread库实现
 ✨反思
优秀文章参考

✨阻塞队列代码——管理任务

✨代码

Log.h
#pragma once

#include
#include
#include
using namespace std;
#include
#include  // Windows


enum
{
   
	SCREEN,ONEFILE,CLASSIFY
};
enum
{
   
	INFO = 10,DEBUG,MERROR,WARING,COUNT
};
class Log
{
   
	mutex mtx;
	Log() {
   }
public:
	static Log log;
	Log& operator=(const Log&) = delete;
	Log(const Log&) = delete;

	string GetFileName(int type)
	{
   
		string ret;
		switch (type)
		{
   
		case INFO:
			ret = "info.txt";
			break;
		case DEBUG:
			ret = "debug.txt";
			break;
		case ERROR:
			ret = "error.txt";
			break;
		case WARING:
			ret = "waring.txt";
			break;
		case COUNT:
			ret = "count.txt";
			break;
		}
		return ret;
	}
	string GetType(int type)
	{
   
		string ret;
		switch (type)
		{
   
		case INFO:
			ret = "[ info ]";
			break;
		case DEBUG:
			ret = "[ debug ]";
			break;
		case MERROR:
			ret = "[ error ]";
			break;
		case WARING:
			ret = "[ waring ]";
			break;
		case COUNT:
			ret = "[ count ]";
			break;
		}
		return ret;
	}
	void WriteToFile(int des,int type,const string& content)
	{
   
		string ret = GetType(type);
		ret += content;
		switch (des)
		{
   
		case SCREEN:
			cout << ret << endl;
			break;
		case CLASSIFY:
			string filename = GetFileName(type);

			{
   
				unique_lock<mutex> lg(mtx);
				FILE* fd = fopen(filename.c_str(), "a");
				char str[100];
				snprintf(str, sizeof(str), "%s\n", ret.c_str());
				fwrite(str, sizeof(char), strlen(str), fd);
				fclose(fd);
			}
			break;
		}
	}
};
Log Log::log;
Task.h
#pragma once

#include
#include
#include
#include
#include
#include
#include

using namespace std;
#include"Log.h"

using _fun_t = function<double()>;

class Task
{
   
public:
	// 引用捕获
	//Task(int a=0, int b=0, char op='+') : _a(a), _b(b), _op(op), _ret()
	//{
   
	//	_hash['+'] = [this] {
   
	//		_ret = (double)_a + _b; 
	//	};
	//	_hash['-'] = [this] {
   
	//		_ret = (double)_a - _b; 
	//	};
	//	_hash['*'] = [this] { 
	//		_ret = (double)_a * _b; 
	//	};
	//	_hash['/'] = [this] {
   
	//		if (_b == 0) _ret = 0;
	//		else _ret = (double)_a / _b;
	//	};
	//	_hash['%'] = [this] {
   
	//		if (_b == 0) _ret = 0;
	//		else _ret = _a % _b;
	//	};
	//}
	// 使用值捕获进行构造
	Task(int a = 0, int b = 0, char op = '+') : _a(a), _b(b), _op(op), _ret()
	{
   
		// 使用参数捕捉并且带有返回值就可以解决问题了
		// 现在就算是浅拷贝也可以
		_hash['+'] = [=]()

你可能感兴趣的:(c++,开发语言,线程池)