Skip to content

Commit

Permalink
update pool
Browse files Browse the repository at this point in the history
  • Loading branch information
gwq5210 committed Aug 16, 2022
1 parent 0b7131a commit e669feb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 13 deletions.
3 changes: 2 additions & 1 deletion examples/thread/thread_pool.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ int main(int argc, char* argv[]) {
GTL_SET_LEVEL(gtl::LogLevel::kDebug);
int task_count = 100;
int thread_count = 200;
gtl::ThreadPool thread_pool(thread_count);
gtl::ThreadPool thread_pool;
thread_pool.Start(thread_count);
GTL_DEBUG("add task begin");
for (int i = 0; i < task_count * thread_count; ++i) {
thread_pool.AddTask(std::bind(Print, std::to_string(i)));
Expand Down
4 changes: 2 additions & 2 deletions src/gtl/thread/thread_pool.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace gtl {

bool ThreadPool::Start(size_t thread_count, const std::string& name /* = "ThreadPool" */) {
set_name(name);
bool ThreadPool::Start(size_t thread_count) {
for (size_t i = 0; i < thread_count; ++i) {
threads_.emplace_back([this]() { this->Run(); });
}
stop_ = false;
return true;
}

Expand Down
34 changes: 24 additions & 10 deletions src/gtl/thread/thread_pool.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,47 @@

namespace gtl {

class ThreadPool {
class IThreadPool {
public:
explicit ThreadPool(size_t thread_count, const std::string& name = "ThreadPool") { Start(thread_count, name); }
~ThreadPool() { Stop(); }
IThreadPool() {}
virtual ~IThreadPool() { Stop(); }
virtual bool Start(size_t thread_count) = 0;
virtual bool AddTask(std::function<void(void)>&& task) = 0;
virtual void Stop() = 0;
virtual bool IsStop() const = 0;

const std::string& name() const { return name_; }
void set_name(const std::string& name) { name_ = name; }
private:
IThreadPool(const IThreadPool& other) = delete;
IThreadPool& operator=(const IThreadPool& other) = delete;
};

bool Start(size_t thread_count, const std::string& name = "ThreadPool");
bool AddTask(std::function<void(void)>&& task);
bool Stop() {
class ThreadPool : public IThreadPool {
public:
ThreadPool() {}
~ThreadPool() { Stop(); }

bool Start(size_t thread_count) override;
bool AddTask(std::function<void(void)>&& task) override;
void Stop() override {
if (stop_) {
return;
}
stop_ = true;
cond_var_.Broadcast();
for (auto& thread : threads_) {
thread.Join();
}
threads_.clear();
}
bool IsStop() const override { return stop_; }

private:
ThreadPool(const ThreadPool& other) = delete;
ThreadPool& operator=(const ThreadPool& other) = delete;

void Run();

std::string name_ = "ThreadPool";
std::atomic_bool stop_{false};
std::atomic_bool stop_{true};
Mutex mutex_;
CondVar cond_var_;
Vector<Thread> threads_;
Expand Down

0 comments on commit e669feb

Please sign in to comment.