简体   繁体   English

在 lambda 函数中捕获 boost::asio::thread_pool

[英]Capturing boost::asio::thread_pool in lambda function

I'm trying to capture thread_pool object in a lambda function.我正在尝试在 lambda 函数中捕获 thread_pool 对象。 This lambda function is called inside a thread.这个 lambda 函数在线程内被调用。 Upon this call, it creates(obtains) a new thread with asio::post.在这个调用中,它使用 asio::post 创建(获取)一个新线程。 However, it throws segmentation fault.但是,它会引发分段错误。 I tried create weak ptr with shared_ptr<thread_pool> but it didn't work as well.我尝试使用 shared_ptr<thread_pool> 创建弱 ptr,但效果不佳。 Simple example written below,下面写一个简单的例子,

#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>

void thread1(std::function<void()> createThread) {
  createThread();
}

void thread2() {
  cout << "You made it" << std::endl;
}

int main(int argc, char **argv) {
  boost::asio::thread_pool pool(std::thread::hardware_concurrency());

  std::function<void()> createThread;
  createThread = [&pool] () {
    boost::asio::post(pool, boost::bind(thread2));
    return true;
  };

  boost::asio::post(pool, boost::bind(thread1, createThread));

  pool.join();

}

It works if I create another thread_pool object inside the lambda function.如果我在 lambda 函数中创建另一个 thread_pool 对象,它会起作用。 However, this is not the right way to do this.但是,这不是执行此操作的正确方法。 Therefore, I am open for your suggestions.因此,我愿意接受您的建议。

Edit: Added libraries to code snippet and removed while loop.编辑:将库添加到代码片段并删除了 while 循环。

I'd simplify:我会简化:

#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>

void thread1(std::function<void()> createThread) {
    createThread();
    while (true) {
        std::cout << "Sleeping" << std::endl;
        sleep(1);
    }
}

void thread2() { std::cout << "You made it" << std::endl; }

int main() {
    boost::asio::thread_pool pool;

    post(pool,
         boost::bind(thread1, [&pool]() { post(pool, boost::bind(thread2)); }));

    pool.join();
}

Note the endl that forces stdout to flush, which helps getting results you can expect.请注意强制标准输出刷新的endl ,这有助于获得您可以预期的结果。

HOWEVER然而

There's a code smell with:有一种代码气味:

  • using explicit "threads" when using a thread-pool使用线程池时使用显式“线程”
  • nullary bind expressions空值bind表达式
  • createThread doesn't (create a thread) createThread没有(创建线程)
  • passing references to execution contexts.传递对执行上下文的引用。 Instead, pass executors相反,通过 executors

Applying these:应用这些:

#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>

using Executor = boost::asio::thread_pool::executor_type;

void task_loop(Executor ex, std::function<void()> task) {
    while (true) {
        post(ex, task);
        sleep(1);
    }
}

void task_function() { std::cout << "Task executes" << std::endl; }

int main() {
    boost::asio::thread_pool pool;

    post(pool, boost::bind(task_loop, pool.get_executor(), task_function));

    pool.join();
}

Prints each second:每秒打印:

Task executes
Task executes
...

Is this one what you look for?这是你要找的吗? :

typedef std::unique_ptr<boost::asio::io_service::work> work_ptr;
std::atomic<bool> closeFlag(false);

int main(int argc, char** argv) {
    boost::asio::io_service service;

    // keep the workers occupied
    work_ptr work(new boost::asio::io_service::work(service));
    boost::thread_group workers;
    for(size_t i = 0; i < std::thread::hardware_concurrency(); ++i) {
        workers.create_thread([&service]() {
            service.run();
        });
    }
    
   service.post([] { std::cout << "You made first job"; });
   service.post([] { std::cout << "You made second job"; });

    while(!closeFlag) {
        boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    }

    service.stop();
    work.reset(); // destroy work object: signals end of work
    workers.join_all(); // wait for all worker threads to finish
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何处理:如果 boost::asio::post 无休止地重复,当 boost::asio::thread_pool 析构函数被触发时? - How to deal: if boost::asio::post is endlessly repeated, when boost::asio::thread_pool destructor is triggered? 可以使用 boost::asio::thread_pool 而不是将 boost::asio::io_context 与 boost::thread::thread_group 结合使用吗? - Can boost::asio::thread_pool be used instead of combining boost::asio::io_context with a boost::thread::thread_group? 在多个线程上发布任务时 boost::asio::thread_pool 线程安全吗? - Is boost::asio::thread_pool thread safe when posting tasks on multiple threads? 我的 boost::asio::thread_pool 中的线程 ID 始终相同 - Thread-ID is always the same in my boost::asio::thread_pool 等到发布到 boost::asio::thread_pool 的作业(与所有作业完全相反)完成? - Wait until A job (as starkly opposed to ALL jobs) posted to boost::asio::thread_pool completes? Helgrind 在简单的 boost::asio::thread_pool 程序中报告同步错误 - Helgrind reports synchronization errors in simple boost::asio::thread_pool program C++线程池使用boost::asio::thread_pool,为什么我不能重用我的线程? - C++ thread pool using boost::asio::thread_pool, why can't I reuse my threads? asio :: thread_pool甚至在调用构造函数之前就失败了 - asio::thread_pool fails before constructor is even called 协程不分布在 asio::thread_pool 线程上 - Coroutines are not distributed over asio::thread_pool threads 在循环中将工作排队到 Boost Thread_Pool - Queueing work into a Boost Thread_Pool within a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM