Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why might threads be considered "evil"?

Tags:

I was reading the SQLite FAQ, and came upon this passage:

Threads are evil. Avoid them.

I don't quite understand the statement "Thread are evil". If that is true, then what is the alternative?

My superficial understanding of threads is:

  • Threads make concurrence happen. Otherwise, the CPU horsepower will be wasted, waiting for (e.g.) slow I/O.
  • But the bad thing is that you must synchronize your logic to avoid contention and you have to protect shared resources.

Note: As I am not familiar with threads on Windows, I hope the discussion will be limited to Linux/Unix threads.

like image 795
pierrotlefou Avatar asked Jul 28 '09 01:07

pierrotlefou


1 Answers

When people say that "threads are evil", the usually do so in the context of saying "processes are good". Threads implicitly share all application state and handles (and thread locals are opt-in). This means that there are plenty of opportunities to forget to synchronize (or not even understand that you need to synchronize!) while accessing that shared data.

Processes have separate memory space, and any communication between them is explicit. Furthermore, primitives used for interprocess communication are often such that you don't need to synchronize at all (e.g. pipes). And you can still share state directly if you need to, using shared memory, but that is also explicit in every given instance. So there are fewer opportunities to make mistakes, and the intent of the code is more explicit.

like image 135
Pavel Minaev Avatar answered Nov 03 '22 02:11

Pavel Minaev