开发者

Simulating Thread with fork()

开发者 https://www.devze.com 2023-03-23 19:31 出处:网络
What\'s yo开发者_运维知识库ur idea about simulating thread with \"fork() function\" and a \"shared memory\" block ...

What's yo开发者_运维知识库ur idea about simulating thread with "fork() function" and a "shared memory" block ...

Is it possible ?

How much is it reasonable to do this for a program ? ( I mean , Will it work well..?)


For starters, don't mix a thread and fork().

A fork gives you a brand new process, which is a copy of the current process, with the same code segments. As the memory image changes (typically this is due to different behavior of the two processes) you get a separation of the memory images, however the executable code remains the same. Tasks do not share memory unless they use some Inter Process Communication (IPC) primitive.

In contrast a thread is another execution thread of the same task. One task can have multiple threads, and the task memory object are shared among threads, therefore shared data must be accessed through some primitive and synchronization objects that allow you to avoid data corruption.


Yes, it is possible, but I cannot imagine it being a good idea, and it would be a real pain to test.

If you have a shared heap, and you make sure all semaphores etc. are allocated in the heap, and not the stack, then there's no inherent reason you couldn't do something like it. There would be some tricky differences though.

For example, anything you do in an interrupt handler in a multi-threaded program can change data used by all the threads, while in a forked program, you would have to send multiple interrupts, which would be caught at different times, and might lead to unintended effects.

If you want threading behavior, just use a thread.


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

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


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

And the answer is, yes you can, but you have to remember to explicitly mark which memory areas you want shared. You can not just share your variables between the processes. Also, you can communicate this way between processes not related to each other at all. It is not limited to processes forked from each other.

Have a look at shared memory or "shm".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号