Boost Asio pattern with GUI and worker thread

后端 未结 3 860
名媛妹妹
名媛妹妹 2021-02-03 13:35

I would like to implement a Boost Asio pattern using a thread for GUI and a worker thread for some socket IO.

The worker thread will use boost::asio::io_service

3条回答
  •  名媛妹妹
    2021-02-03 14:16

    If you have only one worker, then it's rather easy.

    ASIO's handlers are executed by the thread(s) that are calling io_service.run(). In your case, that means that only one thread, the worker one, can execute callback handler. So you need not to worry about thread safety here.

    Your GUI thread, assuming that it has access to one's socket, can call boost::asio::async_write() without problem. The callback handler, however, will be executed in the worker thread.

    From my experience (admitedly limited), I used this pattern:

    1. The business logic thread (could be your GUI thread) can schedule a write to one of its client easily, by calling boost::asio::async_write(): the worker thread will take care of it.
    2. The worker thread start some boost::asio::async_read(), and could be building "business logic packet". What I mean here, is that it construct meaningfull message (could be a subclass of a custom class Packet or Event or w/e you what) from raw data.
    3. When the worker thread has enough data to build such a message, it does, and then enqueue it to a thread-safe queue that the GUI thread will be pulling.
    4. The GUI (or business logic) thread then process the message.

    Let me know if its not clear / if I can be of more help.

提交回复
热议问题