Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of thread_local! #9

Open
serpiente opened this issue Jan 2, 2024 · 3 comments
Open

Use of thread_local! #9

serpiente opened this issue Jan 2, 2024 · 3 comments

Comments

@serpiente
Copy link

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
Copy link
Owner

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
Copy link
Author

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
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants