Ruby fork and thread

I run the program on a machine with two processors, when I make a fork, is it a child created as a native thread, or is it like a green thread / coroutine. Is the child process at the same time as the parent, or is it just parallel?

+7
source share
2 answers

The work of fork () in the general case is to create a new independent process, duplicate the page table and mark all pages that belong to a process called fork () as copy-on-write in this process. Then fork () returns in both processes (the return value allows the corresponding process to find out what it is).

In a system with more than one processor (or processor cores), you can normally (if you have a system with SMP support, which does not interfere with its affinity with the CPU) expect these two processes to use both processors, but you have no guarantee.

On some systems (for example, on Linux), threads are generated the same way, except that the pages belonging to the first process are not marked with copy to write, but instead they belong to both processes (they use the same page table). In other systems, threads can be implemented in different ways, for example. in the user zone, in which case you will not be able to use several processors with threads.

As a side note, the disadvantage of using fork () and starting 2 processes instead of threads is that the processes do not have a common address space, which means that the TLB must be reset in the context switch.

+7
source

It depends on the operating system, programming language, compiler, and runtime library, so I can only give an example: if you use _beginthread on Windows (regardless of whether you use MinGW or MSCRT directly), you use both of your processors. Next, we explain the semantics of “parallel” and “parallel”: they are not exclusive.

0
source

All Articles