同步

If you think your programs crashing before, wait until they crash ten times as fast - **

A thread is short for ‘thread-of-execution’. It represents the sequence of instructions that the CPU has and will execute. To remember how to return from function calls, and to store the values of automatic variables and parameters a thread uses a stack. Almost weirdly, a thread is a process, meaning that creating a thread is similar to fork, except there is no copying meaning no copy on write. What this allows is for a process to share the same address space, variables, heap, file descriptors and etc. The actual system call to create a thread is similar to fork. It’s clone. We won’t go into the specifics, but you can read the http://man7.org/linux/man-pages/man2/clone.2.html keeping in mind that it is outside the direct scope of this course. LWP or Lightweight Processes or threads are preferred to forking for a lot of scenarios because there is a lot less overhead creating them. But in some cases, notably python uses this, multiprocessing is the way to make your code faster.

Processes vs threads

Creating separate processes is useful when

  • When more security is desired. For example, Chrome browser uses different processes for different tabs.

  • When running an existing and complete program then a new process is required, for example starting ‘gcc’.

  • When you are running into synchronization primitives and each process is operating on something in the system.

  • When you have too many threads – the kernel tries to schedule all the threads near each other which could cause more harm than good.

  • When you don’t want to worry about race conditions

  • If one thread blocks in a task (say IO) then all threads block. Processes don’t have that same restriction.

  • When the amount of communication is minimal enough that simple IPC needs to be used.