Two blocking tasks on the same thread

Hello!

Though I have several years of programming experience, I have little experience with C++. So, maybe this topic belongs in the beginner section. I'm familiar with writing async code within a single thread. But, lately, I want more speed.

Generally, my question is this: If I have a blocking web server, can I have a non-blocking periodic timer on the same thread?

The specifics:
- I'm using https://github.com/uNetworking/uWebSockets for a web socket server. For this server "The event loop will block until no more async work is scheduled, like for Node.js." So, after I start the server, no more code will be executed on the server-running thread

- While the server is running, I also need a periodic timer to broadcast messages to the clients at some interval. I've found some ways to implement a periodic timer, but ultimately they all block execution on the thread. Even the boost::asio timer with async_wait() will block once the timer is running.

My conclusion is that I must run this periodic timer in a separate thread, perhaps using std::thread with detach(). Is this reasonable?

P.S.: The preview feature was displaying an empty post before submitting this post. However, now that I'm editing it, the preview feature is working.
Last edited on
I think you are correct to use 2 threads.
I think you are correct to use 2 threads.

Thanks for your response. I'm glad to hear this.
if you are not familiar with c++ and threading, I would do a little simple something before diving into a complex program. for example, take a billion or so random numbers, split it into 4 blocks, and sort them in parallel, then merge them back together and see if you can beat std::sort with it (you can use std::sort on the partitions). No blocking, no race conditions to start out. Then maybe try something that needs a mutex. Then circle back to your bigger project. Just a thought... I find it easy to learn on small dedicated problems first, and threading is kind of a rough topic due to the black arts needed to debug code that is running in parallel.
Thanks for sharing your thoughts. I completely agree that keeping it simple will better facilitate learning and understanding. However, I think my use case is quite simple, and the program is currently working properly. My main concern is that there is a simpler solution for my specific issue. If there isn't a simpler solution, then I understand that I will need to ensure that everything I do in the timer thread must not inadvertently affect my server thread and the other way around.

...

Unfortunately, I've found that uWS is not thread-safe, and therefore I cannot use it to broadcast periodically from some other thread. It seems that uWS has built-in functionality for my situation, but the documentation is sort of a DIY situation. So I'm looking into it. Specifically, `Loop.h`.
Topic archived. No new replies allowed.