从线程内派生安全吗? [英] Is it safe to fork from within a thread?

查看:78
本文介绍了从线程内派生安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我解释一下:我已经在Linux上开发了一个应用程序,该应用程序分叉并执行一个外部二进制文件并等待其完成.结果由fork +进程特有的shm文件传达.整个代码都封装在一个类中.

Let me explain: I have already been developing an application on Linux which forks and execs an external binary and waits for it to finish. Results are communicated by shm files that are unique to the fork + process. The entire code is encapsulated within a class.

现在我正在考虑对进程进行线程化以加快处理速度.有很多不同的类函数实例,它们会分叉并同时执行二进制文件(具有不同的参数),并将结果与​​它们自己的唯一shm文件进行通信.

Now I am considering threading the process in order to speed things up. Having many different instances of class functions fork and execute the binary concurrently (with different parameters) and communicate results with their own unique shm files.

此线程安全吗?如果我在线程中分叉,除了安全起见,还需要注意些什么吗?任何建议或帮助,我们将不胜感激!

Is this thread safe? If I fork within a thread, apart from being safe, is there something I have to watch for? Any advice or help is much appreciated!

推荐答案

fork即使使用线程,也是安全的.派生后,线程在每个进程中都是独立的. (也就是说,线程与分支正交).但是,如果不同进程中的线程使用相同的共享内存进行通信,则必须设计一种同步机制.

forking, even with threads, is safe. Once you fork, the threads are independent per process. (That is, threading is orthogonal to forking). However, if the threads in different processes use the same shared memory to comunicate, you have to devise a synchronization mechanism.

这篇关于从线程内派生安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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