一个简单的C++线程池实现

包含两个队列,一个任务队列和一个线程队列。启动线程池前首先创建任务,将所有任务加入任务队列。

头文件thread_pool.h:

#pragma once
#include
#include
#include
#include
#include
#include
#include

typedef void (*RUNFUC)(void);
/* 任务函数 */

class thread_pool 
{
    public:
        thread_pool(int t_size=3);
        ~thread_pool();

        void start();

        void stop();

        void add_task(void *in_task);

        void set_size(int t_size){t_size=t_size;};

        void do_task();

        bool is_stopped() {return is_stop;};

        void join();
    protected:



    private:
        std::deque task;
        std::vector t_list;
        std::vector runfuc_args;
        int t_size;
        std::mutex m;
        std::condition_variable t_not_full, t_not_empty;
        std::condition_variable task_not_full, task_not_empty;
        bool is_stop;
};

cxx文件thread_pool.cxx:

#include"thread_pool.h"

thread_pool::thread_pool(int t_size) : t_size(t_size), is_stop(false)
{

}


thread_pool::~thread_pool()
{
    if (!is_stopped())
        stop();
}

void thread_pool::start()
{
    for(int i=0; i lck(m);

        while (task.empty())
        {
            task_not_empty.wait(lck);
        }
        auto t_task = task.front();
        task.pop_front();
        lck.unlock();
        t_task();  
    }
}

void thread_pool::add_task(void *in_task)
{
    std::unique_lock lck(m);
    task.push_back((RUNFUC)in_task);
    if (task.size() == 1)
        task_not_empty.notify_one();
}

测试文件pooltest.cxx:

#include
#include
#include
#include"thread_pool.h"


void task_1(void)
{
    std::cout << "Thread id : " << 
    std::this_thread::get_id() << "\t do task\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}

int main(void)
{
    int t_size, task_size;
    std::cout << "Pleaes input the numbers of threads and tasks you want to create:\n";
    std::cin >> t_size >> task_size;
    thread_pool *pool = new thread_pool(t_size);
    for (int i=0; iadd_task((void *)task_1);
    }
    clock_t begin = clock();
    pool->start();
    pool->join();
    clock_t end = clock();
    std::cout << "Time used : " << (end-begin)/CLOCKS_PER_SEC << " s\n";
    delete pool;
    return EXIT_SUCCESS;
}

使用g++进行编译和运行结果:

一个简单的C++线程池实现_第1张图片

 

你可能感兴趣的:(操作系统)