본문 바로가기
C.C++/코드

thread_group

by 겜게준 2018. 4. 24.

#pragma once


#include <vector>

#include <thread>

#include <iostream>


class thread_group

{

private:

 //포인터 컨테이너

std::vector<std::thread *> container;


public:

thread_group()

{

}

virtual ~thread_group()

{

//소멸자 호출시 join 후

join_all();


//쓰레드 delete

for(auto& thread : container) 

delete thread;

};


 //다른 쓰레드그룹 대입 및 복사 금지

thread_group(const thread_group&) = delete;

thread_group& operator=(const thread_group&) = delete;


      //기본 new로 하거나 bind를 통해서 생성된 경우를 위해 template로 선언

template<typename F>

std::thread* create_thread(F thread_func)

{

std::thread* thread = new std::thread(thread_func);

container.push_back(thread);

// 생성 후 관리할 수 있도록 thread 주소값 리턴

return thread;

}


// 직접 생성된 쓰레드를 추가할 경우

void add_thread(std::thread* thread)

{

container.push_back(thread);

}


//모두 join이 필요한 경우 사용

void join_all()

{

for(auto& thread : container)

{

if(thread->joinable())

thread->join();

}

}

};


 표준 라이브러리에서는 지원을 안해서 간단하게 만들었습니다. 자잘한 버그가 있겠지만 추후 계속 수정하도록 하겠습니다.


thread_group.hpp


댓글