在多线程程序中派生 [英] fork in multi-threaded program

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

问题描述

我听说程序中的分支和线程混合可能会很成问题,通常会导致神秘的行为,尤其是在处理共享资源(例如锁,管道,文件描述符)时.但是我永远不会完全理解危险的确切含义以及何时可能发生.如果对此领域有专门知识的人可以在此环境下进行编程时,能详细解释什么陷阱以及需要注意什么,那就太好了.

I've heard that mixing forking and threading in a program could be very problematic, often resulting with mysterious behavior, especially when dealing with shared resources, such as locks, pipes, file descriptors. But I never fully understand what exactly the dangers are and when those could happen. It would be great if someone with expertise in this area could explain a bit more in detail what pitfalls are and what needs to be care when programming in a such environment.

例如,如果我想编写一个从各种不同资源收集数据的服务器,我想过的一个解决方案是让服务器产生一组线程,每个线程都调出另一个程序来执行实际工作,打开管道以从子级取回数据.这些线程中的每一个都响应自己的工作,没有数据交互,并且在收集数据时,主线程有一个队列,这些工作线程会将结果放入队列中.此解决方案可能会出什么问题?

For example, if I want to write a server that collects data from various different resources, one solution I've thought is to have the server spawns a set of threads, each popen to call out another program to do the actual work, open pipes to get the data back from the child. Each of these threads responses for its own work, no data interexchange in b/w them, and when the data is collected, the main thread has a queue and these worker threads will just put the result in the queue. What could go wrong with this solution?

请不要仅通过回答"我的示例场景来缩小答案的范围.与示例无关但有助于提供简洁设计的任何建议,替代解决方案或经验都将非常棒!谢谢!

Please do not narrow your answer by just "answering" my example scenario. Any suggestions, alternative solutions, or experiences that are not related to the example but helpful to provide a clean design would be great! Thanks!

推荐答案

当您确实有一些线程在运行时,分叉的问题是分叉仅复制了一个调用它的线程的CPU状态.好像所有其他线程都立即消失了,无论它们在哪里.

The problem with forking when you do have some threads running is that the fork only copies the CPU state of the one thread that called it. It's as if all of the other threads just died, instantly, wherever they may be.

其结果是未释放锁,并且共享数据(例如malloc堆)可能已损坏.

The result of this is locks aren't released, and shared data (such as the malloc heap) may be corrupted.

pthread确实提供了 pthread_atfork 函数-从理论上讲,您可以在分叉之前获取程序中的所有锁,然后释放它们,然后也许使其生效-但这是有风险的,因为您总是会错过一个.而且,其他线程的堆栈当然也不会释放.

pthread does offer a pthread_atfork function - in theory, you could take every lock in the program before forking, release them after, and maybe make it out alive - but it's risky, because you could always miss one. And, of course, the stacks of the other threads won't be freed.

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

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