//cthreads.h
#pragma once
#include <queue>
#include <thread>
#include <memory>
#include <atomic>
#include "csafe_queue.h"
//线程虚基类
class cthread_task
{
public:
//线程任务处理函数
virtual void task() = 0;
};
class cthreads
{
public:
//新增任务
void push_task(cthread_task *task);
void add_thread();
void del_thread();
void del_all();
size_t count()const;
private:
void thread_run(std::atomic_bool* thread_flag);
csafe_queue<std::shared_ptr<cthread_task>> tasks;
std::queue<std::atomic_bool*> threads;
};
//cthreads.cpp
#include "cthreads.h"
void cthreads::push_task(cthread_task* task)
{
tasks.emplace(task);
}
void cthreads::add_thread()
{
std::atomic_bool* flag = new std::atomic_bool;
threads.push(flag);
flag->store(true);
std::thread(&cthreads::thread_run, this, flag).detach();
}
void cthreads::del_thread()
{
threads.front()->store(false);
threads.pop();
}
void cthreads::del_all()
{
while (!threads.empty())
{
del_thread();
}
}
size_t cthreads::count() const
{
return threads.size();
}
void cthreads::thread_run(std::atomic_bool* thread_flag)
{
while (*thread_flag)
{
std::shared_ptr<cthread_task> task;
bool is_pop = tasks.pop(task);
if(is_pop)
{
task->task();
}else
{
std::this_thread::yield();
}
}
delete thread_flag;
}
//csafe_queue.h
//安全队列
#pragma once
#include <mutex>
#include <list>
template <typename Type>
class csafe_queue
{
public:
using cvalue_type = Type;
using cpointer = Type * ;
using creferenced = Type & ;
using cconst_referenced = const Type&;
template<typename ...Args>
void emplace(Args &&...args)
{
std::lock_guard<std::mutex> lock(_mutex);
_safe_queue.emplace_back(args...);
}
bool pop(creferenced value)
{
std::lock_guard<std::mutex> lock(_mutex);
if (_safe_queue.empty())
{
return false;
}
value = _safe_queue.front();
_safe_queue.pop_front();
return true;
}
private:
std::mutex _mutex;
std::list<Type> _safe_queue;
};
//mian.cpp
#include <iostream>
class ctask_1 :public cthread_task
{
public:
void task() override
{
std::cout << "task_1\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
class ctask_2 :public cthread_task
{
public:
void task() override
{
std::cout << "task_2\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
class ctask_3 :public cthread_task
{
public:
void task() override
{
std::cout << "task_3\n";
std::this_thread::sleep_for(std::chrono::seconds(3));
}
};
int main()
{
cthreads threads;
for (int i= 0; i < 10000; i++)
{
if(i%3==0)
{
threads.push_task(new ctask_1);
}else if(i % 3 == 1)
{
threads.push_task(new ctask_2);
}
else if (i % 3 == 2)
{
threads.push_task(new ctask_3);
}else
{
}
}
threads.add_thread();
threads.add_thread();
threads.add_thread();
std::getchar();
threads.del_thread();
std::cout << threads.count()<<"/n";
std::getchar();
threads.del_thread();
std::cout << threads.count() << "/n";
std::getchar();
}
出处忘了,在B站上看到