#include <thread>
#include <atomic>
#include <queue>
#include <mutex>
#include <unistd.h>
#include <condition_variable>
#include <iostream>
template <typename T>
class cond_thread {
typedef void (*FuncPtr)(T data, const int thId);
public:
cond_thread(FuncPtr funcPtr, const int thId):m_funPtr(funcPtr),m_thId(thId){
std::cout<<"===construct======"<<std::endl;
m_pThread = std::make_shared<std::thread>(&cond_thread::run,this);
}
~cond_thread(){
if (m_run.load()){
m_run.store(false);
m_task_cv.notify_all();
if(m_pThread != nullptr && m_pThread->joinable()){
m_pThread->join();
}
}
std::cout<<"===distruct======"<<std::endl;
}
void addTask(T data){
m_tasks.push(data);
m_task_cv.notify_all();
}
protected:
void run(){
while(m_run.load()){
std::unique_lock<std::mutex> lock{ m_lock };
m_task_cv.wait(lock, [this]{
return !m_run.load() || !m_tasks.empty();
});
if (!m_run.load() && m_tasks.empty()){
return;
}
T task = std::move(m_tasks.front());
m_tasks.pop();
if(m_funPtr != nullptr){
m_funPtr(task, m_thId);
}
}
}
private:
const int m_thId;
std::atomic<bool> m_run{ true };
std::shared_ptr<std::thread> m_pThread;
std::condition_variable m_task_cv;
std::queue<T> m_tasks;
std::mutex m_lock;
FuncPtr m_funPtr;
};
-----------------上述代码待完成 thread 是怎么把成员函数作为--------------------------------
template<typename _Callable, typename... _Args, typename = _Require<__not_same<_Callable>>>
explicit
thread(_Callable&& __f, _Args&&... __args)
{
auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
using _Invoker_type = _Invoker<__decayed_tuple<_Callable, _Args...>>;
_M_start_thread(_S_make_state<_Invoker_type>( std::forward<_Callable>(__f), std::forward<_Args>(__args)...), __depend);
}
-------------------------------------------------------------------------------------
#include "cond_thread.hpp"
#include <vector>
#include <Windows.h>
using namespace std;
void test(short data, const int thId){
cout<<thId<<"=>"<<data<<endl;
fflush(stdout);
}
class Test{
public:
Test(){
m_thpool.emplace_back( new cond_thread<short>(test, 0));
m_thpool.emplace_back( new cond_thread<short>(test, 1));
m_thpool.emplace_back( new cond_thread<short>(test, 2));
}
void testTask(){
int i=0;
for(auto& val : m_thpool){
val->addTask(i);
//cout<<"input"<<i<<endl;
++i;
}
Sleep(1);
}
~Test(){
for(auto& val : m_thpool){
delete val;
}
m_thpool.clear();
}
private:
vector<cond_thread<short>*> m_thpool;
};
int main()
{
Test test;
test.testTask();
//Sleep(10);
return 0;
}