线程和fork()。我该如何处理? [英] Threads and fork(). How can I deal with that?

查看:214
本文介绍了线程和fork()。我该如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

fork in multi-threaded program

应用程序使用fork()并且可能被开发为多线程,为安全地编程这种应用程序考虑什么是拇指规则/指南?

If I have an application which employs fork() and might be developed as multithreaded, what are the thumb rules/guidelines to consider to safely program this kind of applications?

推荐答案


  1. (Main)Process [0] Monothread - > fork() - >(Child)Process [1]多线程: OK!

    处理[1] 会导致内存崩溃或混乱,不会触摸处理[0] 的地址空间(除非您使用共享R / W记忆...但这是另一个主题的自己)。
    在Linux中,默认情况下所有 fork()ed 内存是写入时复制。假设 Process [0] 是单线程的,当我们调用 fork()时,所有可能的互斥基元应该

  1. (Main) Process[0] Monothread --> fork() --> (Child) Process[1] Multithreaded: OK!
    If Process[1] crashes or messes around with memory it won't touch address space of Process[0] (unless you use shared R/W memory... but this is another topic of its own).
    In Linux by default all fork()ed memory is Copy On Write. Given that Process[0] is monothreaded, when we invoke fork() all possible mutual exclusion primitives should be generally in an unlocked state.

(Main)Process [0] Multithreaded - > fork ] Mono / Multithread BAD!

如果您执行多线程程序,您的mutex和许多其他线程同步基元在进程[1]中处于未定义状态。你可以使用 pthread_atfork(),但如果你使用库,你可能会掷骰子,希望是幸运的。因为一般来说,你不需要知道库的实现细节。

(Main) Process[0] Multithreaded --> fork() --> (Child) Process[1] Mono/Multithread: BAD!
If you fork() a Multithreaded process your mutexes and many other thread synchronization primitives will likely be in an undefined state in Process[1]. You can work around with pthread_atfork() but if you use libraries you might as well roll a dice and hope to be lucky. Because generally you don't (want to) know the implementation details of libraries.

fork()到多线程进程中,你可以更快地处理/读取/聚合你的数据(在Child进程),而不必关心你的进程的稳定性。从(主)。如果您的主进程具有很多内存的数据集,并且您不想复制/重新加载它以安全地处理另一个进程(子进程)中的数据,这将非常有用。这样,原始进程是稳定的,并且独立于数据聚合/操作过程( fork()ed )。

The advantages of fork() into a multithreaded process are that you could manipulate/read/aggregate your data quicker (in the Child process), without having to care about stability of the process you fork() from (Main). This is useful if your main process has a dataset of a lot of memory and you don't want to duplicate/reload it to safely process the data in another process (Child). This way the original process is stable and independent from the data aggregation/manipulation process (fork()ed).

原始进程通常会比以多线程方式开发的速度更慢。

Of course this means that the original process will generally be slower than it might be if developed in multithreaded fashion. But again, this is the price you might want to be paying for more stability.

如果您的主要流程是多线程,则 refrain 不会使用 fork()

If instead your main process is multithreaded, refrain from using fork(). It's going to be a proper mess to implement it in a stable way.

干杯

这篇关于线程和fork()。我该如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆