ibraheemdev / too-many-web-servers

https://ibraheem.ca/posts/too-many-web-servers/
101 stars 7 forks source link

Use of thread_local! #9

Open serpiente opened 10 months ago

serpiente commented 10 months ago

Hello,

Thanks for the awesome write-up. Really enjoying it. I was going through the code for the asynchronous webserver and couldn't understand why you used thread_local for the reactor and scheduler. Intuitively I understand. We would like to have a thread for the reactor and scheduler so as to not block. I couldn't see that we actually use threads in the code. So is there a reason to use them? I tried removing it and using a Lazy type to make it work. I am new to rust in general so I might be missing something obvious.

ibraheemdev commented 10 months ago

thread_local let's you create variables local to each thread, in our case the main thread, guarded by the LocalKey::get API so they can't be shared. This lets us use single-threaded interior mutability like RefCell. With a global static we would have to use types with synchronization, like sync::Lazy.

serpiente commented 10 months ago

Thanks for the response. My follow-up questions would be. My understanding is that the program only has one main thread right now. If so, is it necessary to still use the thread_local to prevent sharing between threads given there are no other threads?

ibraheemdev commented 5 months ago

static variables are required to implement Sync because it is impossible for the compiler to know if we access it from multiple threads or not. In this case we could use unsafe because we know our program is single-threaded, but that isn't sound in general for a runtime library.