我可以拥有一个无锁的lambda队列吗? [英] Can I have a boost lock-free queue of lambdas?
问题描述
我正在尝试实现一个跨多个线程工作的消息传递系统. boost::lockfree::queue
似乎是一个不错的选择,但是我在创建std::function
或boost::function
类型的队列时遇到了麻烦,因为它们显然没有琐碎的分配和析构函数,这是boost::lockfree::queue
的要求
I'm trying to implement a messaging system that will work across multiple threads. boost::lockfree::queue
seemed like a good direction to go in, unfortunately I'm having trouble creating a queue of either std::function
or boost::function
types as apparently they don't have trivial assignment and destructor's which is a requirement of boost::lockfree::queue
.
我的以下代码:
#include <cassert>
//#include <functional>
#include <iostream>
#include <boost/function.hpp>
#include <boost/lockfree/queue.hpp>
int main()
{
boost::lockfree::queue<boost::function<void(int)>> queue;
assert(queue.is_lock_free());
for(int j = 0; j < 50; ++j) {
queue.push([] (int i) { std::cout << i << std::endl; });
}
int i = 0;
boost::function<void(int)> functor;
while (queue.pop(functor)) {
functor(i++);
}
}
产生以下输出:
In file included from /usr/include/boost/integer.hpp:23:0,
from /usr/include/boost/function/function_base.hpp:21,
from /usr/include/boost/function/detail/prologue.hpp:17,
from /usr/include/boost/function.hpp:24,
from lockfree.cpp:5:
/usr/include/boost/lockfree/queue.hpp: In instantiation of ‘class boost::lockfree::queue<boost::function<void(int)> >’:
lockfree.cpp:10:54: required from here
/usr/include/boost/lockfree/queue.hpp:81:5: error: static assertion failed (boost::has_trivial_destructor<T>::value)
BOOST_STATIC_ASSERT((boost::has_trivial_destructor<T>::value));
^
/usr/include/boost/lockfree/queue.hpp:85:5: error: static assertion failed (boost::has_trivial_assign<T>::value)
BOOST_STATIC_ASSERT((boost::has_trivial_assign<T>::value));
有什么办法可以使这项工作成功吗?
Is there any way to make this work?
推荐答案
如果可以的话,您仍然可以将 stateless lambda与原始函数指针一起使用:
You could still use stateless lambdas with raw function pointers, if that's an option:
#include <cassert>
#include <functional>
#include <iostream>
#include <boost/function.hpp>
#include <boost/lockfree/queue.hpp>
int main() {
//boost::lockfree::queue<boost::function<void(int)>> queue(50);
boost::lockfree::queue<void (*)(int)> queue(50);
assert(queue.is_lock_free());
for (int j = 0; j < 50; ++j) {
queue.push([](int i) { std::cout << i << std::endl; });
}
int i = 0;
boost::function<void(int)> functor;
while (queue.pop(functor)) {
functor(i++);
}
}
http://coliru.stacked-crooked.com/a/d57770e3be029760
这篇关于我可以拥有一个无锁的lambda队列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!