-
Notifications
You must be signed in to change notification settings - Fork 224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug report: When sub-task are performed quickly, the results are inaccurate #39
Comments
If I add thread-sleep, the results will be 6. void push(const int& index) {
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
for (auto& i : v1[index]) {
std::lock_guard<std::mutex> m{mtx};
q.push(i);
}
} Is there some bugs? |
when |
I wrote an inelegant solution. When the thread pool is closed, the task queue is checked to see if there are any tasks left. If so, execution continues. void shutdown() {
m_shutdown = true;
m_conditional_lock.notify_all();
for (int i = 0; i < m_threads.size(); ++i) {
if(m_threads[i].joinable()) {
m_threads[i].join();
}
}
bool dequeued;
std::function<void()> func;
while (m_queue.size()) {
{
std::unique_lock<std::mutex> lock(m_conditional_mutex);
dequeued = m_queue.dequeue(func);
}
if (dequeued) {
func();
}
}
} But this would lose the performance benefits of multithreading. Is there a better solution? |
OK, I think this plan is better. I will send pull request, Thank you for writing such good code that I can use in my application program. void operator()() {
std::function<void()> func;
bool dequeued;
while (!m_pool->m_shutdown) {
{
std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
if (m_pool->m_queue.empty()) {
m_pool->m_conditional_lock.wait(lock);
}
dequeued = m_pool->m_queue.dequeue(func);
}
if (dequeued) {
func();
}
}
// If the task queue is not empty, continue obtain task from task queue,
// the multithread continues execution until the queue is empty
while (!m_pool->m_queue.empty()) {
{
std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
dequeued = m_pool->m_queue.dequeue(func);
if (dequeued) {
func();
}
}
}
} |
The output of the above code is not accurate.
The text was updated successfully, but these errors were encountered: