I have an HTTP server that I am writing using HTTP listener, and I would like to somehow declare certain variables as accessible from anywhere within a thread.
I thought of using a dictionary: Dictionary</*[type of Thread ID here]*/,ThreadData>
, but I'm concerned there might be threading issues. ThreadData
would probably be a class instance, but I might use a struct, depending on which would be more efficient.
Would there be an advantage to using a concurrent dictionary? Is there another way that is more thread-safe?
I am currently using ThreadPool.QueueUserWorkItem
. I don't know for sure that this uses a new thread for each item. If not then I could also key it to the context.
Update: According to ThreadPool class - MSDN, it does reuse threads. And it does not clear thread data.
When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.
But to answer your question, any thread can access any global variable currently in scope. There is no notion of passing variables to a thread. It has a single global variable with a getter and setter function, any thread can call either the getter or setter at any time.
Because threads within a process share the same memory map and hence share all global data (static variables, global variables, and memory that is dynamically-allocated via malloc or new), mutual exclusion is a critical part of application design.
ThreadSafe threadSafe = new ThreadSafe(); for (int i = 0; i < 10; i++) { threadSafe. executor. execute(new MyRunnable(threadSafe)); } ... private static class MyRunnable implements Runnable { private final ThreadSafe threadSafe; public MyRunnable(ThreadSafe threadSafe) { this. threadSafe = threadSafe; } ...
Almost certainly. I answered the question in a very narrow sense: how do I modify a global variable, without any consideration for how you modify it safely.
One solution would be to use a public static field, with the ThreadStatic
attribute:
[ThreadStatic] public static int ThreadSpecificStaticValue;
A static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With