Can Someone Explain Threads to Me? [closed] Can Someone Explain Threads to Me? [closed] multithreading multithreading

Can Someone Explain Threads to Me? [closed]


This is a very broad topic. But here are the things I would want to know if I knew nothing about threads:

  • They are units of execution within a single process that happen "in parallel" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via different means. Switching is called "context switching", and there is some overhead associated with this.

  • They can share memory! This is where problems can occur. I talk about this more in depth in a later bullet point.

  • The benefit of parallelizing your application is that logic that uses different parts of the machine can happen simultaneously. That is, if part of your process is I/O-bound and part of it is CPU-bound, the I/O intensive operation doesn't have to wait until the CPU-intensive operation is done. Some languages also allow you to run threads at the same time if you have a multicore processor (and thus parallelize CPU-intensive operations as well), though this is not always the case.

  • Thread-safe means that there are no race conditions, which is the term used for problems that occur when the execution of your process depends on timing (something you don't want to rely on). For example, if you have threads A and B both incrementing a shared counter C, you could see the case where A reads the value of C, then B reads the value of C, then A overwrites C with C+1, then B overwrites C with C+1. Notice that C only actually increments once!

  • A couple of common ways avoid race conditions include synchronization, which excludes mutual access to shared state, or just not having any shared state at all. But this is just the tip of the iceberg - thread-safety is quite a broad topic.

I hope that helps! Understand that this was a very quick introduction to something that requires a good bit of learning. I would recommend finding a resource about multithreading in your preferred language, whatever that happens to be, and giving it a thorough read.


There are four things you should know about threads.

  1. Threads are like processes, but they share memory.

  2. Threads often have hardware, OS, and language support, which might make them better than processes.

  3. There are lots of fussy little things that threads need to support (like locks and semaphores) so they don't get the memory they share into an inconsistent state. This makes them a little difficult to use.

  4. Locking isn't automatic (in the languages I know), so you have to be very careful with the memory they (implicitly) share.


Threads don't speed up applications. Algorithms speed up applications. Threads can be used in algorithms, if appropriate.