Simulate a stream with fork ()

What do you think of thread simulation using the fork () and shared memory functions ...

Is it possible?

How reasonable is this to do for the program? (I mean, does this work well ??)

+6
source share
4 answers

Yes, it is possible, but I can’t imagine that this is a good idea, and it would be a real pain to experience.

If you have a common bunch, and you make sure that all the semaphores, etc. allocated on the heap, not on the stack, then there is no inherent reason why you could not do something like that. However, there would be some complex differences.

For example, everything you do in an interrupt handler in a multi-threaded program can change the data used by all threads, while in a branched program you have to send several interrupts that will be caught at different times, and can lead to unintended consequences.

If you want thread behavior, just use a thread.

+2
source

For starters, do not use mix stream and fork () .

The fork gives you a whole new process, which is a copy of the current process with the same code segments. As the memory image changes (as a rule, this is due to the different behavior of the two processes), you get a separation of the memory images, but the executable code remains unchanged. Tasks do not exchange memory unless they use the Inter Process Communication (IPC) primitive.

In contrast, a thread is a different thread in the execution of the same task. One task can have several threads, and the task memory object is distributed between threads, therefore, access to shared data should be through some primitive and synchronization objects, which help to avoid data corruption.

+4
source

AFAIK, fork will create a separate process with its own context, stack, and so on. Depends on what you mean by "imitation" ...

You can check this out: http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them

+1
source

A few answers here focus on "don't mix plug and threads." But the way I read your question is this: "Can you use two different processes and still quickly and conveniently communicate with shared memory between them, just like threads have access to each other's memory?"

And the answer is yes, you can, but you must remember to explicitly mark which areas of memory you want to use. You cannot just share your variables between processes. In addition, you can communicate in this way between processes that are not connected to each other at all. This is not limited to processes bifurcated with each other.

Look at shared memory or "shm" .

+1
source

Source: https://habr.com/ru/post/893792/


All Articles