带有线程安全队列的C ++ 11事件循环(C++11 event loop with thread safe queue)
我想创建一个事件循环类,它将在它自己的线程上运行,支持将任务添加为
std::functions
并执行它们。 为此,我从这里使用SafeQueue: https ://stackoverflow.com/a/16075550/1069662class EventLoop { public: typedef std::function<void()> Task; EventLoop(){ stop=false; } void add_task(Task t) { queue.enqueue(t); } void start(); void stop() { stop = true; } private: SafeQueue<Task> queue; bool stop; }; void EventLoop::start() { while (!stop) { Task t = queue.dequeue(); // Blocking call if (!stop) { t(); } } cout << "Exit Loop"; }
然后,你会像这样使用它:
EventLoop loop; std::thread t(&EventLoop::start, &loop); loop.add_task(myTask); // do smth else loop.stop(); t.join();
我的问题是:如何优雅地停止线程? 由于阻塞队列调用,此处不能退出循环。
I want to create an event loop class that will run on it's own thread, support adding of tasks as
std::functions
and execute them. For this, I am using the SafeQueue from here: https://stackoverflow.com/a/16075550/1069662class EventLoop { public: typedef std::function<void()> Task; EventLoop(){ stop=false; } void add_task(Task t) { queue.enqueue(t); } void start(); void stop() { stop = true; } private: SafeQueue<Task> queue; bool stop; }; void EventLoop::start() { while (!stop) { Task t = queue.dequeue(); // Blocking call if (!stop) { t(); } } cout << "Exit Loop"; }
Then, you would use it like this:
EventLoop loop; std::thread t(&EventLoop::start, &loop); loop.add_task(myTask); // do smth else loop.stop(); t.join();
My question is: how to stop gracefully the thread ? Here stop cannot exit the loop because of the blocking queue call.
原文:https://stackoverflow.com/questions/26441912
更新时间:2024-02-06 15:02
最满意答案
<td> <input type="checkbox" name="item-{{item.bed}}" #myItem (change)="OnCheckboxSelect(item.id, $event)" > </td>
在组件中:
@ViewChildren('myItem') item; selectedIds = []; OnCheckboxSelect(id, event) { if (event.target.checked === true) { this.selectedIds.push({id: id, checked: event.target.checked}); console.log('Selected Ids ', this.selectedIds); } if (event.target.checked === false) { this.selectedIds = this.selectedIds.filter((item) => item.id !== id); } }
我能够以这种方式获得我想要的东西。
<td> <input type="checkbox" name="item-{{item.bed}}" #myItem (change)="OnCheckboxSelect(item.id, $event)" > </td>
In component:
@ViewChildren('myItem') item; selectedIds = []; OnCheckboxSelect(id, event) { if (event.target.checked === true) { this.selectedIds.push({id: id, checked: event.target.checked}); console.log('Selected Ids ', this.selectedIds); } if (event.target.checked === false) { this.selectedIds = this.selectedIds.filter((item) => item.id !== id); } }
I was able to get what I want in this way.
相关问答
更多-
jquery mobile本地和环境中显示问题[2023-06-25]
checkbox -
如何在 jQuery Mobile 的 Listview 中动态移除某一条的图标[2023-09-01]
checkbox -
您可以将change事件添加到md-checkbox并将该对象传递给函数。 维护一个array ,跟踪哪些被checked和unchecked checked ,并根据这个数组更新数组。 HTML:要使用ngModel你必须允许绑定输入。 你的输入必须位于form标签内,这个角标转换成他自己的特殊形式。 在窗体中包装输入并添加#f="ngForm"