【问题标题】:Asio thread context and connection is null when trying to use in another thread尝试在另一个线程中使用时,Asio 线程上下文和连接为空
【发布时间】:2023-01-04 23:19:29
【问题描述】:

我在堆上创建 Client 变量,然后连接到 main 中的服务器,一切正常,但是当我分离其他线程并尝试从中调用函数时,我的消息没有到达我调试的服务器并看到该线程上下文并且连接本身被取消。第一张截图来自主线,第二张来自另一个线程

First screenshot

Second screenshot

这是我的客户端类代码:

template <typename T>
        class client_interface
        {
        public:
            client_interface()
            {}

            virtual ~client_interface()
            {
                // If the client is destroyed, always try and disconnect from server
                Disconnect();
            }

        public:
            // Connect to server with hostname/ip-address and port
            bool Connect(const std::string& host, const uint16_t port)
            {
                try
                {
                    // Resolve hostname/ip-address into tangiable physical address
                    asio::ip::tcp::resolver resolver(m_context);
                    asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, std::to_string(port));

                    // Create connection
                    m_connection = std::make_unique<connection<T>>(connection<T>::owner::client, m_context, asio::ip::tcp::socket(m_context), m_qMessagesIn);

                    // Tell the connection object to connect to server
                    m_connection->ConnectToServer(endpoints);

                    // Start Context Thread
                    thrContext = std::thread([this]() { m_context.run(); });
                }
                catch (std::exception& e)
                {
                    std::cerr << "Client Exception: " << e.what() << "\n";
                    return false;
                }
                return true;
            }

            // Disconnect from server
            void Disconnect()
            {
                // If connection exists, and it's connected then...
                if (IsConnected())
                {
                    // ...disconnect from server gracefully
                    m_connection->Disconnect();
                }

                // Either way, we're also done with the asio context...             
                m_context.stop();
                // ...and its thread
                if (thrContext.joinable())
                    thrContext.join();

                // Destroy the connection object
                m_connection.release();
            }

            // Check if client is actually connected to a server
            bool IsConnected()
            {
                if (m_connection)
                    return m_connection->IsConnected();
                else
                    return false;
            }

        public:
            // Send message to server
            void Send(const message<T>& msg)
            {
                if (IsConnected())
                    m_connection->Send(msg);
            }

            // Retrieve queue of messages from server
            tsqueue<owned_message<T>>& Incoming()
            {
                return m_qMessagesIn;
            }

        protected:
            // asio context handles the data transfer...
            asio::io_context m_context;
            // ...but needs a thread of its own to execute its work commands
            std::thread thrContext;
            // The client has a single instance of a "connection" object, which handles data transfer
            std::unique_ptr<connection<T>> m_connection;

        private:
            // This is the thread safe queue of incoming messages from server
            tsqueue<owned_message<T>> m_qMessagesIn;
        };

试图从另一个线程运行上下文,但没有成功。

【问题讨论】:

  • 你的问题到底是什么?
  • 您应该在执行上下文中发布大多数操作。不确定哪些是必要的。否则它不起作用。
  • @Quimby 如何使用来自其他线程的客户端连接变量?它只适用于主线程,但不适用于其他线程
  • 请出示 minimal reproducible example,我猜你的 client_interface 对象已被破坏
  • @Quimby 我将在几分钟内发布最小的可重现示例

标签: c++ multithreading sockets boost-asio asio


【解决方案1】:

所以这很奇怪,但我刚刚创建了一个空项目,一切似乎都正常

network.h

[Link to pastebin][1]


Server.cpp

[Link to pastebin][2]

Client.cpp

[Link to pastebin][3]


  [1]: https://pastebin.com/ytJsYCUf
  [2]: https://pastebin.com/cYNq8Ed0
  [3]: https://pastebin.com/VTQveMNL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多