早在 2010 年,Herb Sutter 就提倡在 article 中使用事件对象而不是裸线。在 Dobb 博士那里。
这是一个 C++11 版本:
class Active {
public:
typedef std::function<void()> Message;
Active(const Active&) = delete;
void operator=(const Active&) = delete;
Active() : done(false) {
thd = std::unique_ptr<std::thread>(new std::thread( [=]{ this->run(); } ) );
}
~Active() {
send( [&]{ done = true; } );
thd->join();
}
void send(Message m) { mq.push_back(m); }
private:
bool done;
message_queue<Message> mq; // a thread-safe concurrent queue
std::unique_ptr<std::thread> thd;
void run() {
while (!done) {
Message msg = mq.pop_front();
msg(); // execute message
} // note: last message sets done to true
}
};
类可以这样使用:
class Backgrounder {
public:
void save(std::string filename) { a.send( [=] {
// ...
} ); }
void print(Data& data) { a.send( [=, &data] {
// ...
} ); }
private:
PrivateData somePrivateStateAcrossCalls;
Active a;
};
我想支持具有非 void 返回类型的成员函数。但是我无法想出一个很好的设计来实现它,即不使用可以容纳异构类型对象(如 boost::any)的容器。
欢迎提出任何想法,尤其是使用 C++11 功能(如 std::future 和 std::promise)的答案。
最佳答案
这需要一些工作。
首先写task<Sig> . task<Sig>是 std::function只希望它的论点是可 move 的,而不是可复制的。
你的内部类型 Messages将会是 task<void()> .所以你可以偷懒,拥有你的task如果您愿意,只支持空函数。
其次,send 创建一个 std::packaged_task<R> package(f); .然后它从任务中获取 future ,然后 move package进入您的消息队列。 (这就是为什么你需要一个只能 move 的 std::function ,因为 packaged_task 只能被 move )。
然后您返回 future来自 packaged_task .
template<class F, class R=std::result_of_t<F const&()>>
std::future<R> send(F&& f) {
packaged_task<R> package(std::forward<F>(f));
auto ret = package.get_future();
mq.push_back( std::move(package) );
return ret;
}
客户可以捕获std::future并使用它(稍后)获取回调的结果。
有趣的是,您可以编写一个非常简单的仅 move 空任务,如下所示:
template<class R>
struct task {
std::packaged_task<R> state;
template<class F>
task( F&& f ):state(std::forward<F>(f)) {}
R operator()() const {
auto fut = state.get_future();
state();
return f.get();
}
};
但这效率低得离谱(打包任务中包含同步内容),并且可能需要一些清理。我觉得它很有趣,因为它使用了 packaged_task仅限 move std::function部分。
就个人而言,我有足够的理由想要只 move 任务(在这个问题中)感觉只 move std::function值得写。下面是一个这样的实现。它没有经过大量优化(可能与大多数 std::function 一样快),也没有调试,但设计合理:
template<class Sig>
struct task;
namespace details_task {
template<class Sig>
struct ipimpl;
template<class R, class...Args>
struct ipimpl<R(Args...)> {
virtual ~ipimpl() {}
virtual R invoke(Args&&...args) const = 0;
};
template<class Sig, class F>
struct pimpl;
template<class R, class...Args, class F>
struct pimpl<R(Args...), F>:ipimpl<R(Args...)> {
F f;
R invoke(Args&&...args) const final override {
return f(std::forward<Args>(args)...);
};
};
// void case, we don't care about what f returns:
template<class...Args, class F>
struct pimpl<void(Args...), F>:ipimpl<void(Args...)> {
F f;
template<class Fin>
pimpl(Fin&&fin):f(std::forward<Fin>(fin)){}
void invoke(Args&&...args) const final override {
f(std::forward<Args>(args)...);
};
};
}
template<class R, class...Args>
struct task<R(Args...)> {
std::unique_ptr< details_task::ipimpl<R(Args...)> > pimpl;
task(task&&)=default;
task&operator=(task&&)=default;
task()=default;
explicit operator bool() const { return static_cast<bool>(pimpl); }
R operator()(Args...args) const {
return pimpl->invoke(std::forward<Args>(args)...);
}
// if we can be called with the signature, use this:
template<class F, class=std::enable_if_t<
std::is_convertible<std::result_of_t<F const&(Args...)>,R>{}
>>
task(F&& f):task(std::forward<F>(f), std::is_convertible<F&,bool>{}) {}
// the case where we are a void return type, we don't
// care what the return type of F is, just that we can call it:
template<class F, class R2=R, class=std::result_of_t<F const&(Args...)>,
class=std::enable_if_t<std::is_same<R2, void>{}>
>
task(F&& f):task(std::forward<F>(f), std::is_convertible<F&,bool>{}) {}
// this helps with overload resolution in some cases:
task( R(*pf)(Args...) ):task(pf, std::true_type{}) {}
// = nullptr support:
task( std::nullptr_t ):task() {}
private:
// build a pimpl from F. All ctors get here, or to task() eventually:
template<class F>
task( F&& f, std::false_type /* needs a test? No! */ ):
pimpl( new details_task::pimpl<R(Args...), std::decay_t<F>>{ std::forward<F>(f) } )
{}
// cast incoming to bool, if it works, construct, otherwise
// we should be empty:
// move-constructs, because we need to run-time dispatch between two ctors.
// if we pass the test, dispatch to task(?, false_type) (no test needed)
// if we fail the test, dispatch to task() (empty task).
template<class F>
task( F&& f, std::true_type /* needs a test? Yes! */ ):
task( f?task( std::forward<F>(f), std::false_type{} ):task() )
{}
};
是库类 move 任务对象的第一个草图。它还使用一些 C++14 的东西(std::blah_t 别名)——替换 std::enable_if_t<???>与 typename std::enable_if<???>::type如果您是仅支持 C++11 的编译器。
请注意 void返回类型技巧包含一些稍微有问题的模板重载技巧。 (在标准的措辞下是否合法还有待商榷,但每个 C++11 编译器都会接受它,如果不合法则很可能成为合法的)。
关于c++ - 事件对象的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30854070/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案