What does threadsafe mean? What does threadsafe mean? multithreading multithreading

What does threadsafe mean?


Eric Lippert has a nice blog post entitled What is this thing you call "thread safe"? about the definition of thread safety as found of Wikipedia.

3 important things extracted from the links :

“A piece of code is thread-safe if it functions correctly duringsimultaneous execution by multiple threads.”

“In particular, it must satisfy the need for multiple threads toaccess the same shared data, …”

“…and the need for a shared piece of data to be accessed by only onethread at any given time.”

Definitely worth a read!


In the simplest of terms threadsafe means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen. So, you add some extra code to prevent those bad things. For example, if two people were writing the same document at the same time, the second person to save will overwrite the work of the first person. To make it thread safe then, you have to force person 2 to wait for person 1 to complete their task before allowing person 2 to edit the document.


Wikipedia has an article on Thread Safety.

This definitions page (you have to skip an ad - sorry) defines it thus:

In computer programming, thread-safe describes a program portion or routine that can be called from multiple programming threads without unwanted interaction between the threads.

A thread is an execution path of a program. A single threaded program will only have one thread and so this problem doesn't arise. Virtually all GUI programs have multiple execution paths and hence threads - there are at least two, one for processing the display of the GUI and handing user input, and at least one other for actually performing the operations of the program.

This is done so that the UI is still responsive while the program is working by offloading any long running process to any non-UI threads. These threads may be created once and exist for the lifetime of the program, or just get created when needed and destroyed when they've finished.

As these threads will often need to perform common actions - disk i/o, outputting results to the screen etc. - these parts of the code will need to be written in such a way that they can handle being called from multiple threads, often at the same time. This will involve things like:

  • Working on copies of data
  • Adding locks around the critical code
  • Opening files in the appropriate mode - so if reading, don't open the file for write as well.
  • Coping with not having access to resources because they're locked by other threads/processes.