Skip to content

Commit 887f76f

Browse files
committed
feat(thread_pool): add run_future method
1 parent 6047f2d commit 887f76f

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

thread/ThreadPool.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,14 @@ void ThreadPool::start(int numThreads)
4747

4848
void ThreadPool::stop()
4949
{
50+
printf("starting to stop the pool.\n");
5051
running_ = false;
5152
cond_.notifyAll();
5253
for_each(threads_.begin(),
5354
threads_.end(),
5455
boost::bind(&muduo::Thread::join, _1));
56+
threads_.clear();
57+
printf("stop the pool successfully.\n");
5558
}
5659

5760
void ThreadPool::run(const Task& task)

thread/ThreadPool.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include <boost/ptr_container/ptr_vector.hpp>
1818

1919
#include <deque>
20+
#include <future>
2021

2122
namespace muduo
2223
{
@@ -34,6 +35,23 @@ class ThreadPool : boost::noncopyable
3435

3536
void run(const Task& f);
3637

38+
template<typename Func, typename... Args>
39+
inline auto run_future(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>
40+
{
41+
if (threads_.empty()) {
42+
func(args...);
43+
}
44+
using ret_type = typename std::result_of<Func(Args...)>::type;
45+
auto task = std::make_shared<std::packaged_task<ret_type()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
46+
auto ret = task->get_future();
47+
do {
48+
MutexLockGuard lock(mutex_);
49+
queue_.push_back([task]() { (*task)(); });
50+
cond_.notify();
51+
} while (0);
52+
return std::move(ret);
53+
}
54+
3755
private:
3856
void runInThread();
3957
Task take();

thread/test/ThreadPool_test.cc

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ void printString(const std::string& str)
1717
int main()
1818
{
1919
muduo::ThreadPool pool("MainThreadPool");
20-
pool.start(5);
2120

21+
22+
pool.start(5);
2223
pool.run(print);
2324
pool.run(print);
2425
for (int i = 0; i < 100; ++i)
@@ -32,5 +33,22 @@ int main()
3233
pool.run(boost::bind(&muduo::CountDownLatch::countDown, &latch));
3334
latch.wait();
3435
pool.stop();
36+
37+
printf("Testing run_future\n");
38+
pool.start(5);
39+
pool.run(print);
40+
pool.run(print);
41+
std::vector<std::future<void>> futures;
42+
for (int i = 0; i < 100; ++i)
43+
{
44+
char buf[32];
45+
snprintf(buf, sizeof buf, "task %d", i);
46+
futures.emplace_back(std::move(pool.run_future(boost::bind(printString, std::string(buf)))));
47+
}
48+
for (auto& future : futures)
49+
{
50+
future.get();
51+
}
52+
pool.stop();
3553
}
3654

0 commit comments

Comments
 (0)