特点
- 可以设置线程池中线程的优先级,然而只有linux系统支持。
- 可以动态增加或减少线程池中线程数量。
接口
class ThreadPool {
public:
virtual ~ThreadPool() {}
// Wait for all threads to finish.
// Discard those threads that did not start
// executing
virtual void JoinAllThreads() = 0;
// Set the number of background threads that will be executing the
// scheduled jobs.
virtual void SetBackgroundThreads(int num) = 0;
virtual int GetBackgroundThreads() = 0;
// Get the number of jobs scheduled in the ThreadPool queue.
virtual unsigned int GetQueueLen() const = 0;
// Waits for all jobs to complete those
// that already started running and those that did not
// start yet. This ensures that everything that was thrown
// on the TP runs even though
// we may not have specified enough threads for the amount
// of jobs
virtual void WaitForJobsAndJoinAllThreads() = 0;
// Submit a fire and forget jobs
// This allows to submit the same job multiple times
virtual void SubmitJob(const std::function<void()>&) = 0;
// This moves the function in for efficiency
virtual void SubmitJob(std::function<void()>&&) = 0;
};
class ThreadPoolImpl : public ThreadPool {
public:
ThreadPoolImpl();
~ThreadPoolImpl();
ThreadPoolImpl(ThreadPoolImpl&&) = delete;
ThreadPoolImpl& operator=(ThreadPoolImpl&&) = delete;
// Implement ThreadPool interfaces
// Wait for all threads to finish.
// Discards all the jobs that did not
// start executing and waits for those running
// to complete
void JoinAllThreads() override;
// Set the number of background threads that will be executing the
// scheduled jobs.
void SetBackgroundThreads(int num) override;
int GetBackgroundThreads() override;
// Get the number of jobs scheduled in the ThreadPool queue.
unsigned int GetQueueLen() const override;
// Waits for all jobs to complete those
// that already started running and those that did not
// start yet
void WaitForJobsAndJoinAllThreads() override;
// Make threads to run at a lower kernel priority
// Currently only has effect on Linux
void LowerIOPriority();
// Ensure there is at aleast num threads in the pool
// but do not kill threads if there are more
void IncBackgroundThreadsIfNeeded(int num);
// Submit a fire and forget job
// These jobs can not be unscheduled
// This allows to submit the same job multiple times
void SubmitJob(const std::function<void()>&) override;
// This moves the function in for efficiency
void SubmitJob(std::function<void()>&&) override;
// Schedule a job with an unschedule tag and unschedule function
// Can be used to filter and unschedule jobs by a tag
// that are still in the queue and did not start running
void Schedule(void (*function)(void* arg1), void* arg, void* tag,
void (*unschedFunction)(void* arg));
// Filter jobs that are still in a queue and match
// the given tag. Remove them from a queue if any
// and for eac