如何在单独的线程中正确组织一小部分代码的工作?

发布于 2025-02-13 02:57:40 字数 1248 浏览 0 评论 0原文

我想每20秒在单独的线程中运行一小部分C ++代码。

// std::unique_ptr<databaseServer> database
// std::vector<std::unique_ptr<databaseServer>> databases_list_

    while (is_work_) {

        for (auto& database : databases_list_) {
            if (db_conn_status == connection_status::connected) {

                { // I want to run this piece of code in a separate thread
                std::string stats_query = "SYSTEM_VOC";
                auto db_stats = database->send_command(stats_query, command_type::get_stats);
                const auto getdata_result = cmd_parser::getstat_command(db_stats);
                if (getdata_result.success == true)
                   mtrcs.inc_stat_data(getdata_result.queue_voc);
                }

                auto db_respond = database->send_command(receive_channel_cmd, command_type::get_data);

            }
            else if (db_conn_status == connection_status::disconnected) {
                   database->reconnect();
            }
        }   
        std::this_thread::sleep_for(std::chrono::seconds(processing_period_));
    }

问题是,在此代码中,有一个“数据库”参数,该参数类型为std :: simolor_ptr。
因此“数据库”参数在“ while”循环中更改。
我不知道如何在单独的线程中正确整理这一小件代码的工作。

I want to run a small piece of C++ code in a separate thread every 20 seconds.

// std::unique_ptr<databaseServer> database
// std::vector<std::unique_ptr<databaseServer>> databases_list_

    while (is_work_) {

        for (auto& database : databases_list_) {
            if (db_conn_status == connection_status::connected) {

                { // I want to run this piece of code in a separate thread
                std::string stats_query = "SYSTEM_VOC";
                auto db_stats = database->send_command(stats_query, command_type::get_stats);
                const auto getdata_result = cmd_parser::getstat_command(db_stats);
                if (getdata_result.success == true)
                   mtrcs.inc_stat_data(getdata_result.queue_voc);
                }

                auto db_respond = database->send_command(receive_channel_cmd, command_type::get_data);

            }
            else if (db_conn_status == connection_status::disconnected) {
                   database->reconnect();
            }
        }   
        std::this_thread::sleep_for(std::chrono::seconds(processing_period_));
    }

The problem is that in this code there is a "database" parameter which is of type std::unique_ptr.
So the 'database' parameter changes in the 'while' loop.
I don't know how to properly organize the work of this small piece of code in a separate thread.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文