写线程池的几个小bug注意

初始化『()』不能随便用,如果这个类用默认形参的构造函数,或者没有形参,那就不要加括号初始化,特别是当存在默认形参情况,它会默认你加的是『0』的形参

Threadpool(size_t threadNum = 4,size_t queSize = 10);

*如果构造类的时候价括号,会报错

 int main()
Threadpool threadpool();//这个构造有问题
threadpool.start();

error: request for member ‘start’ in ‘threadpool’, which is of non-class type ‘wd::Threadpool()’ . threadpool.start();


头文件和源文件尽量分开,如果在源文件中写了一些函数实现,务必保证必要的声明,一般的引用只要前置声明就行不需要头文件,但是比如构造函数在头文件,就需要保证头文件

include "TaskQueue.h"

include "Thread.h" //构造函数中,_threads隐藏了vector的构造,这时候只前置声明 『class Thread』是不够的,此时要创建Thread,但是没有头文件,无法创建

include

include

using std::vector;
using std::unique_ptr;

namespace wd
{
class Task;
class Thread;

class Threadpool
{
friend class WorkerThread;
public:
Threadpool(size_t threadNum = 4,size_t queSize = 10)
:_threadNum(threadNum)
,_queSize(queSize)
,_taskque(queSize)
,_isExit(false)
{
_threads.reserve(_threadNum);
}
~Threadpool();
void start();
void stop();
void addTask(Task *task);
private:
Task * getTask();
void threadfunc();
private:
size_t _threadNum;
size_t _queSize;
vector<unique_ptr > _threads;
TaskQueue _taskque;
bool _isExit;
};
}

posted @ 2019-08-08 00:28  prome6  阅读(203)  评论(0)    收藏  举报