Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions muduo/base/ThreadPool.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ ThreadPool::ThreadPool(const string& nameArg)
notFull_(mutex_),
name_(nameArg),
maxQueueSize_(0),
running_(false)
running_(false),
havetask_(false)
{
}

Expand Down Expand Up @@ -86,6 +87,7 @@ void ThreadPool::run(Task task)
assert(!isFull());

queue_.push_back(std::move(task));
havetask_=true;
notEmpty_.notify();
}
}
Expand All @@ -108,6 +110,10 @@ ThreadPool::Task ThreadPool::take()
notFull_.notify();
}
}
else
{
havetask_=false;
}
return task;
}

Expand All @@ -125,7 +131,7 @@ void ThreadPool::runInThread()
{
threadInitCallback_();
}
while (running_)
while (running_||havetask_)
{
Task task(take());
if (task)
Expand Down Expand Up @@ -154,3 +160,4 @@ void ThreadPool::runInThread()
}
}


1 change: 1 addition & 0 deletions muduo/base/ThreadPool.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ class ThreadPool : noncopyable
std::deque<Task> queue_ GUARDED_BY(mutex_);
size_t maxQueueSize_;
bool running_;
bool havetask_;
};

} // namespace muduo
Expand Down
23 changes: 23 additions & 0 deletions muduo/base/tests/ThreadPool_test.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include<iostream>
#include "muduo/base/ThreadPool.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/base/CurrentThread.h"
Expand All @@ -17,6 +18,12 @@ void printString(const std::string& str)
usleep(100*1000);
}

void selfprint()
{
std::cout<<"这是一次调用"<<"\n";
usleep(5000*1000);
}

void test(int maxSize)
{
LOG_WARN << "Test ThreadPool with max queue size = " << maxSize;
Expand Down Expand Up @@ -86,6 +93,20 @@ void test2()
LOG_WARN << "test2 Done";
}

void test3()
{
muduo::ThreadPool pool("miniThread");
pool.setMaxQueueSize(10);
pool.start(3);
for(int i=0;i<8;++i)
{
pool.run(selfprint);
}
usleep(100000);
pool.stop();
std::cout<<"线程池运行退出了"<<std::endl;
}

int main()
{
test(0);
Expand All @@ -94,4 +115,6 @@ int main()
test(10);
test(50);
test2();
test3();
}