Threads and variable lock

I’m looking into thread programming. I understand that you need to lock a variable so two different threads can’t change a variable at the same time (and produce wrong values).

I have two threads: The main thread and a worker thread. The main thread executes at every Update(), the worker thread changes a variable at an interval of 200ms. The main thread only reads this variable, never writes to it. Do I still need to lock that variable?

I think not, because the main thread only reads it. Is that right?

I’m new to threads and I’m not sure if I completely understand them.

You probably do not need locks in this case. However, you should retrieve a copy of the variable and use that copy exclusively in the main thread. If you didn’t and you accessed the variable multiple times (within one Update() call), you might be reading different values, which can be problematic.

The only issue you might have is with that variable holding an object reference. If an object reference is used, you might have issues with the worker thread modifying the object after you have retrieved its reference. If the worker thread does not touch the object after assigning it to the variable, then you should be ok.

Multi-threading is a headache causing concept in programming, and is often considered an advanced concept because of this situation. I would advise reading up as much as you can about the topic. Unless you really need it, I would avoid using multithreading (use co-routines if you can).

The worker thread could run at any time including while the main thread is running. Take the following situation.

  1. Line 1 of main thread executes.
  2. Main thread pauses.
  3. Entire worker thread executes.
  4. Main thread finishes.

This can occur for any line in the main thread.

For primitive types accessed only once in the main thread there shouldn’t be a problem. Check for problems arising from the worker thread changing the variable while the main thread is running. Things to look for include the main thread accessing the variable more than once in the function, or an array changing size, or objects being destroyed.