I have to make a thread-safe work queue which can have work popped on in different threads and it will process it on a worker thread. The work can be very generic so I was thinking using lambdas with capture as a good way to allow this. I have the following code as a starter:
#include <iostream>
#include <vector>
#include <functional>
typedef std::function<void()> Task;
typedef std::vector<Task> TaskQueue;
class Queue
{
public:
void flush() {
for (auto it : m_queue) {
it();
}
}
// will add thread safe locks later.
void queue(Task task) {
m_queue.push_back(task);
}
private:
TaskQueue m_queue;
};
Queue q;
class WorkMaker
{
public:
WorkMaker(int inA) : m_a(inA) {}
void MakeWork() {
q.queue([&]{
std::cout << this->m_a << std::endl;
});
}
private:
int m_a;
};
int main()
{
WorkMaker w1(1);
WorkMaker w2(2);
w1.MakeWork();
w2.MakeWork();
q.flush();
return 0;
}
Is there something inherently unperformant about this code or will the compiler optimize it out? Also is passing a lambda into a std::function
argument by value copying the lambda or just the pointer to it?
EDIT:
I think i can solve the problem of memory ownership by using shared_ptr's and passing them into the lambda instead. Consider the following modification:
typedef std::function<void()> Task;
typedef std::deque<Task> TaskQueue;
class Queue
{
public:
void flush() {
while (!m_queue.empty()) {
auto it = m_queue.front();
m_queue.pop_front();
it();
}
}
// will add thread safe locks later.
void queue(Task task) {
m_queue.push_back(task);
}
private:
TaskQueue m_queue;
};
Queue q;
class WorkMaker : public std::enable_shared_from_this<WorkMaker>
{
public:
WorkMaker(int inA) : m_a(inA) {}
~WorkMaker() { std::cout << "Destroy " << m_a << std::endl; }
void MakeWork() {
std::shared_ptr<WorkMaker> self = shared_from_this();
q.queue([self]{
std::cout << self->m_a << std::endl;
});
}
int m_a;
};
int main()
{
{
auto w1 = std::make_shared<WorkMaker>(1);
auto w2 = std::make_shared<WorkMaker>(2);
w1->MakeWork();
w2->MakeWork();
}
q.flush();
return 0;
}
I get the desired output as :
1
Destroy 1
2
Destory 2
The std::function
will make a private copy of the function pointer, lambda or whatever it refers to. Typically, this copy is referenced from the std::function
object so that further copying is later avoided.
There is nothing particularly slow with using std::function
objects this way. However, you should probably think about replacing the std::vector
by a std::deque
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.