Skip to content
Open
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
46 changes: 46 additions & 0 deletions cond_variable_instead_sleep_for.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
--- worker.hpp Thu Mar 22 23:20:12 2018
+++ worker.hpp Sat Mar 24 22:28:13 2018
@@ -2,6 +2,8 @@

#include <atomic>
#include <thread>
+#include <condition_variable>
+#include <mutex>

namespace tp
{
@@ -78,6 +80,8 @@
Queue<Task> m_queue;
std::atomic<bool> m_running_flag;
std::thread m_thread;
+ std::mutex m_conditional_mutex;
+ std::condition_variable m_conditional_lock;
};


@@ -121,6 +125,7 @@
inline void Worker<Task, Queue>::stop()
{
m_running_flag.store(false, std::memory_order_relaxed);
+ m_conditional_lock.notify_all();
m_thread.join();
}

@@ -140,6 +145,7 @@
template <typename Handler>
inline bool Worker<Task, Queue>::post(Handler&& handler)
{
+ m_conditional_lock.notify_one();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should do the notification after you have added the job to the queue otherwise the worker might try to pull the job too soon

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мммммммм, in theory may be. In practice....hardly. Also, how you imagine such implementation? I see only one way - additional local variable requires, so more assembler, slower execution... No, not so good idea.

Copy link

@KayEss KayEss Jun 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're going to worry about the cost of that it might be more interesting to look at the call to notify_one you have for every posted job. Compared to that cost saving the bool result is essentially free.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're going to worry about the cost of that it might be more interesting to look at the call to notify_one you have for every posted job. Compared to that cost saving the bool result is essentially free.

Take a look on my own fork of this library. Done long time ago. :) This PR is years old :)

Anyway, you can make you own fork, perform benchmark and compare. :)

return m_queue.push(std::forward<Handler>(handler));
}

@@ -171,7 +177,8 @@
}
else
{
- std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ std::unique_lock<std::mutex> lock(m_conditional_mutex);
+ m_conditional_lock.wait(lock);
}
}
}