我正在嘗試使用本機 C 創建一個執行緒池,并且我正在使用“C Concurrency in Action”一書中的代碼清單。我遇到的問題是,當我提交的作業項多于執行緒數時,并非所有作業項都完成了。在下面的簡單示例中,我嘗試提交 runMe() 函式 200 次,但該函式僅運行 8 次。這似乎不應該發生,因為在代碼中,work_queue 與作業執行緒是分開的。這是代碼:
#include "iostream"
#include "ThreadPool.h"
void runMe()
{
cout << "testing" << endl;
}
int main(void)
{
thread_pool pool;
for (int i = 0; i < 200; i )
{
std::function<void()> myFunction = [&] {runMe(); };
pool.submit(myFunction);
}
return 0;
}
ThreadPool.h 類
#include <queue>
#include <future>
#include <list>
#include <functional>
#include <memory>
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue() {}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(mut);
data_queue.push(std::move(new_value));
data_cond.notify_one();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = std::move(data_queue.front());
data_queue.pop();
}
bool try_pop(T& value)
{
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return false;
value = std::move(data_queue.front());
data_queue.pop();
return true;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(mut);
return data_queue.empty();
}
int size()
{
return data_queue.size();
}
};
class join_threads
{
std::vector<std::thread>& threads;
public:
explicit join_threads(std::vector<std::thread>& threads_) : threads(threads_) {}
~join_threads()
{
for (unsigned long i = 0; i < threads.size(); i )
{
if (threads[i].joinable())
{
threads[i].join();
}
}
}
};
class thread_pool
{
std::atomic_bool done;
threadsafe_queue<std::function<void()> > work_queue;
std::vector<std::thread> threads;
join_threads joiner;
void worker_thread()
{
while (!done)
{
std::function<void()> task;
if (work_queue.try_pop(task))
{
task();
numActiveThreads--;
}
else
{
std::this_thread::yield();
}
}
}
public:
int numActiveThreads;
thread_pool() : done(false), joiner(threads), numActiveThreads(0)
{
unsigned const thread_count = std::thread::hardware_concurrency();
try
{
for (unsigned i = 0; i < thread_count; i )
{
threads.push_back(std::thread(&thread_pool::worker_thread, this));
}
}
catch (...)
{
done = true;
throw;
}
}
~thread_pool()
{
done = true;
}
template<typename FunctionType>
void submit(FunctionType f)
{
work_queue.push(std::function<void()>(f));
numActiveThreads ;
}
int size()
{
return work_queue.size();
}
bool isQueueEmpty()
{
return work_queue.empty();
}
};
關于如何正確使用 work_queue 的任何想法?
uj5u.com熱心網友回復:
當pool在 結束時被銷毀main,您的解構式設定done,使您的作業執行緒退出。
main在設定標志之前,您應該讓解構式(或者可能,如果您想讓它成為可選)等待佇列耗盡。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/382670.html
