利用C++11并发库实现的线程池(超级好用、超级强大)

直接上代码如下:

#ifndef THREADS_CONTAINER_H
#define THREADS_CONTAINER_H

#include <queue>
#include <atomic>
#include <future>
#include <thread>
#include <functional>
#include <stdexcept>

class ThreadsContainer
{
    using Task = std::function<void()>;
public:
    ThreadsContainer(int size = std::thread::hardware_concurrency() / 2){
        CreateTasks(size);
    }
    ~ThreadsContainer(){
        isRun = false;
		condition.notify_all();
		for (std::thread& thread : container) {
			if (thread.joinable()){
				thread.join();
            }
		}
    }
    ThreadsContainer(const ThreadsContainer &) = delete;
    ThreadsContainer &operator=(const ThreadsContainer &) = delete;

    template<class F, class... Args>
    auto Start(F&& f, Args&&... args)
        -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))> {
        using ReturnType = decltype(std::forward<F>(f)(std::forward<Args>(args)...));

        auto task = std::make_shared<std::packaged_task<ReturnType()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        {
            std::unique_lock<std::mutex> lock{taskLock};
            if (!isRun) {
                exit(1);
            }

            allTasks.emplace([task] { (*task)(); });
        }

        condition.notify_one();
        return task->get_future();
    }
private:
    void CreateTasks(unsigned int size)
    {
        for (; size > 0; --size)
		{
			container.emplace_back( [this]{
				while (true)
				{
					Task task;
					{
						std::unique_lock<std::mutex> lock{ taskLock };
						condition.wait(lock, [this] {
							return !isRun || !allTasks.empty();
						});
						if (!isRun && allTasks.empty()){
							return;
                        }
						task = std::move(allTasks.front()); 
						allTasks.pop();
					}
					task();
				}
			});
		}
    }
  
    std::vector<std::thread> container;
    std::mutex taskLock;
    std::condition_variable condition;
    std::atomic<bool> isRun{ true };
    std::queue<Task> allTasks;
};

#endif

知识点说明:

调用方法示例:

1.普通无参函数作为线程函数

int doWork()  // 线程执行函数必须有返回值
{
    return 1;
}

int main(int argc, char** argv)
{
    ThreadsContainer threadsConter;
    auto retThreadReturnValue = threadsConter.Start(doWork); 
    auto retValue = retThreadReturnValue.get(); // 获取线程函数的返回结果
}

2.普通有参函数作为线程函数

int doWork(int param)  // 线程执行函数必须有返回值
{
    std::cout << param;
    return 1;
}

int main(int argc, char** argv)
{
    ThreadsContainer threadsConter;
    auto retThreadReturnValue = threadsConter.Start(doWork, 100); // 这里可以根据自己的业务需求,传入多个参数
    auto retValue = retThreadReturnValue.get();
}

2.类的静态无参成员函数作为线程函数

class My
{
public:

    static int doWork_static()  // 线程执行函数必须有返回值
    {

        return 1;
    }
   
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    CThreadsContainer threadsConter;
    threadsConter.Start(&My::doWork_static); // 类的静态无参数成员函数作为线程函数
    auto retValue = retThreadReturnValue.get();
    ...... // 其它代码略
}

3.类的静态有参成员函数作为线程函数

class My
{
public:

    static int doWork_static_hasParam(int a)  // 线程执行函数必须有返回值
    {

        return 1;
    }
   
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    CThreadsContainer threadsConter;
    threadsConter.Start(&My::doWork_static_hasParam, 10); // 类的静态无参数成员函数作为线程函数
    auto retValue = retThreadReturnValue.get();
    ...... // 其它代码略
}

3.类的无参成员函数作为线程函数

class My
{
public:

    int doWork()  // 线程执行函数必须有返回值
    {

        return 1;
    }
    
};


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    CThreadsContainer threadsConter;
    My h;
    auto f = std::bind(&My::doWork, &h);
    auto retThreadReturnValue = threadsConter.Start(f);
    auto retValue = retThreadReturnValue.get();
    ...... // 其它代码略
}

 4.类的有参成员函数作为线程函数

class My
{
public:

    int doWork_hasParam(int a)  // 线程执行函数必须有返回值
    {

        return 1;
    }

};


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    CThreadsContainer threadsConter;
    My h;
    auto f = std::bind(&My::doWork_hasParam, &h, std::placeholders::_1);
    auto retThreadReturnValue = threadsConter.Start(f, 96);
    auto retValue = retThreadReturnValue.get();
    ...... // 其它代码略
}

还可以用lmba表达式、函数对象作为线程函数,在此不再举例。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值