Threads and fork(): think twice before mixing them.

本文探讨了在多线程程序中使用fork函数的问题,包括关键代码段和互斥锁的状态问题,以及库函数可能带来的不确定性。同时介绍了如何通过设置文件描述符标志来避免安全风险,并推荐使用pthread_atfork函数来解决这些问题。

原文地址:http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them

 

When debugging a program I came across a bug that was caused by using fork(2) in a multi-threaded program. I thought it's worth to write some words about mixing POSIX threads with fork(2) because there are non-obvious problems when doing that.

What happens after fork() in a multi-threadeed program


The fork(2) function creates a copy of the process, all memory pages are copied, open file descriptors are copied etc. All this stuff is intuitive for a UNIX programmer. One important thing that differs the child process from the parent is that the child has only one thread. Cloning the whole process with all threads would be problematic and in most cases not what the programmer wants. Just think about it: what to do with threads that are suspended executing a system call? So the fork(2) call clones just the thread which executed it.

What are the problems


 

Critical sections, mutexes


The non-obvious problem in this approach is that at the moment of the fork(2) call some threads may be in critical sections of code, doing non-atomic operations protected by mutexes. In the child process the threads just disappears and left data half-modified without any possibility to "fix" them, there is no way to say what other threads were doing and what should be done to make the data consistent. Moreover: state of mutexes is undefined, they might be unusable and the only way to use them in the child is to call pthread_mutex_init() to reset them to a usable state. It's implementation dependent how mutexes behave after fork(2) was called. On my Linux machine locked mutexes are locked in the child.

Library functions


Problem with mutexes and critical code sections implies another non-obvious issue. It's theoretically possible to write your code executed in threads so that you are sure it's safe to call fork when such threads run but in practice there is one big problem: library functions. You're never sure if a library function you are using doesn't use global data. Even if it is thread safe, it may be achieved using mutexes internally. You are never sure. Even system library functions that are thread-safe may use locks internally. One non-obvious example is the malloc() function which at least in multi-threaded programs on my system uses locks. So it's not safe to call fork(2) at the moment some other thread calls malloc()! What the standard says about it? After fork(2) in a multi-threaded program you may only call async-safe functions (listed in signal(7)). It's similar limitation to the list of functions you are allowed to call in a signal handler and the reason is similar: in both cases the thread might be "interrupted" while executing a function.

Here is a list of few functions that use locks internally on my system, just to show you that really almost nothing is safe:

  • malloc()
  • stdio functions like printf() - this is required by the standard.
  • syslog()

execve() and open file descriptors


It seems that calling execve(2) to start another program is the only sane reason you would like to call fork(2) in a multi-threaded program. But even doing that has at least one problem. When calling execve(2) one must remember that open file descriptors remain open and the program that was executed may read and write to them. It creates a problem if you leave open file descriptor at the time you call execve(2) that was not intended to be visible by the executed program. It even creates security issues in some cases. There is a solution for that: you must set the FD_CLOEXEC flag on all file descriptors using fcntl(2) so they are automatically closed on new programs execution. Unfortunately it's not as simple in multi-threaded program. When using fcntl(2) to set the FD_CLOEXEC flag there is a race:

  
  1. fd = open ( "file" , O_RDWR | O_CREAT | O_TRUNC , 0600 );
  2. if (fd < 0 ) {
  3. perror ( "open()" );
  4. return 0;
  5. }
  6.  
  7. fcntl (fd , F_SETFD , FD_CLOEXEC );

When another thread executes fork(2) and execve(2) just between this thread does open(2) but before fcntl(2) a new program is started having this file descriptor duplicated. This is not what we want. A solution was created with newer standards (like POSIX.1-2008) and newer Linux kernel (changes in 2.6.23 and later). We now have O_CLOEXEC flag to the open(2) function, so the whole operation of opening a file and setting the FD_CLOEXEC flag is atomic.

There are other ways to create file descriptors than using open(2): duplicating them with dup(2), creating sockets with socket(2) etc. All those functions have now a flag similar to O_CLOEXEC or a newer version that can take similar flag (some of them, like dup2(2) does not have a flags argument, so dup3(2) was created).

It's worth to mention that a similar thing may happen in a single threaded program when it does fork(2) and execve(2) in a signal handler. This operation is perfectly legal because both of the functions are async-safe and can be called from a signal handler, but the problem is the program may be interrupted between open(2) and fcntl(2).

For more information about the new API to set FD_CLOEXEC flag see Ulrich Drepper's blog: Secure File Descriptor Handling.

Useful system functions: pthread_atfork()


One useful function that tries to solve the problem with fork(2) in multi-threaded programs is pthread_atfork(). It has the following prototype:

  
  1. int pthread_atfork ( void ( *prepare ) ( void ) , void ( *parent ) ( void ) , void ( *child ) ( void ) );

It allows to set handler functions that will be automatically executed on fork call:

  • prepare - Called just before a new process is created.
  • parent - Called after a new process is created in the parent.
  • child - Called after a new process is created in the child.

The purpose of this call is to deal with critical sections of a multi-threaded program at the time fork(2) is called. A typical scenario is when in the prepare handler mutexes are locked, in the parent handler unlocked and in the child handler reinitialized.

Summary


In my opinion there are so many problems with fork(2) in multi-threaded programs that it's almost impossible to do it right. The only clear case is to call execve(2) in the child process just after fork(2). If you want to do something more, just do it some other way, really. From my experience it's not worth trying to make the fork(2) call save, even with pthread_atfork(). I truly hope you read this article before hitting problems described here.

Resources


 

 

内容概要:本文针对不对称电网故障下T型三电平逆变器的低电压穿越(LVRT)问题,提出了一种多目标协同控制策略,并通过Simulink进行仿真实现。该策略综合考虑了有功功率、无功功率、负序电流、中点电位平衡及谐波抑制等多个控制目标,采用正负序分离、双闭环调节与多目标优化算法协同作用,实现了故障期间并网电流的精确控制与系统稳定运行。研究重点在于提升逆变器在电网电压跌落与不平衡等恶劣工况下的适应能力,确保其符合并网技术规范。仿真结果表明,该策略在动态响应速度、电能质量改善和系统鲁棒性方面均表现出优越性能; 适合人群:具备电力电子、新能源并网或自动控制等相关专业背景,从事逆变器控制、微电网或柔性输电系统研究的研发人员及研究生;熟悉Simulink仿真工具者更佳; 使用场景及目标:①研究不对称电网故障下三电平逆变器的低电压穿越控制方法;②掌握多目标协同控制策略的设计思路与实现手段;③通过Simulink仿真平台复现并验证先进控制算法,服务于科研论文撰写、项目开发或工程优化; 阅读建议:建议结合Simulink仿真模型同步学习,重点关注正负序分离锁相、多目标权重分配与中点电位控制模块的实现细节,深入理解控制策略在暂态过程中的协同机制,并尝试调整故障条件与参数以评估系统鲁棒性。
内容概要:本文围绕构网型变流器在不对称电网条件下的正负序阻抗解耦特性展开研究,基于Simulink搭建详细的仿真模型,系统分析其在弱电网环境中的动态响应与稳定性表现。研究通过建立变流器的小信号数学模型,采用频率扫描法(扫频法)对正负序阻抗进行精确辨识,并利用Nyquist图与Bode图开展频域稳定性分析,深入揭示构网型变流器在不同电网强度下的失稳机理与交互特性。重点探讨了解耦控制策略的设计原理及其对改善系统稳定性的关键作用,旨在为高比例新能源接入背景下电力系统的稳定运行与控制器优化提供理论支撑与技术路径。; 适合人群:具备电力电子、自动控制及电力系统分析等相关专业知识,从事新能源并网、微电网控制、变流器建模与稳定性研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①掌握构网型变流器正负序阻抗的建模与仿真方法;②理解基于小信号分析的扫频辨识技术与频域稳定性判据的应用流程;③应用于新型电力系统中构网型设备的并网稳定性评估与控制器参数优化设计;④为相关课题的仿真复现、论文撰写与项目研究提供完整的技术参考与实现方案。; 阅读建议:建议读者结合文中所述Simulink仿真模型,亲自动手实现阻抗扫频与稳定性分析全过程,重点关注锁相环、电流控制环等关键模块的小信号建模方法,并对照Nyquist与Bode图进行多工况对比分析,以深化对系统频域特性的理解与工程应用能力。
源码下载地址: https://pan.quark.cn/s/a4b39357ea24 在Linux操作系统平台上进行C++语言开发,达成串行通信功能是一项核心且关键的技能,特别是在嵌入式系统设计、设备管理或物联网解决方案中。此"Linux下C++实现简易串口交互"范例展示了一个基础性的架构,旨在协助程序员了解怎样运用C++与计算机的串行端口(COM端口)进行互动,完成数据的发送及接收任务。接下来将详尽阐述相关技术要点。 1. **串行通信原理**: 串行通信是一种历史悠久的通信机制,借助串行接口来传输信息。在Linux环境中,串行端口通常被映射为/dev/ttySx的路径,其中x代表端口的编号,例如/dev/ttyS0或/dev/ttyUSB0等。串行通信所涉及的重要参数包含波特率、数据位数、停止位数及校验类型等。 2. **C++与系统接口调用**: 若要在C++中操作串口,必须借助系统级调用或第三方库。本范例可能直接运用了包含在<termios.h>头文件中的函数,比如使用tcgetattr()和tcsetattr()来配置串口特性,open()和close()用于串口的开启与关闭,以及write()和read()负责数据的发送与接收。 3. **<termios.h>中的结构体**: struct termios结构体是控制串口行为的决定性组件,它包含了串口的多种配置选项,如波特率(Baud Rate)、数据位(Data Bits)、停止位(Stop Bits)和校验位(Parity Bit)等。程序员需要通过cfsetispeed()和cfsetospeed()来设定输入和输出的波特率,而c_cflag字段则用于设定其他串口配置。 4. **串口初始化...
下载代码方式:https://pan.quark.cn/s/a4b39357ea24 DELL故障诊断灯是戴尔计算机系统内一种极具价值的硬件故障检测设备。它被集成在计算机的主板上,通过呈现不同的颜色以及闪烁模式来指示灯,协助用户和维修人员迅速识别潜在的硬件故障,进而缩短了诊断时间并优化了维修效率。接下来将具体阐述DELL故障诊断灯的运作机制、常规灯码的象征意义以及如何运用这些信息来处理故障。 一、运作机制 DELL故障诊断灯系统一般包含电源指示灯和位于计算机背部或侧面的诊断指示灯。电源指示灯用于展示系统的供电状态,而诊断指示灯则负责对各个核心硬件单元(例如内存、中央处理器、硬盘驱动器、显卡等)进行故障排查。当系统遭遇异常时,这些灯会以特定的亮灯或闪烁方式来构成一个灯码序列,用以揭示问题的类型和潜在的原因。 二、灯码象征意义 1. 电源指示灯: - 绿色持续点亮:意味着电源已成功接入且系统在正常运作。 - 黄色频闪:或许暗示电源适配器或电池存在故障。 - 不亮或呈现红色:可能存在电源方面的难题,例如电源适配器未正确连接或已损坏。 2. 诊断指示灯: - 灯码1-4:通常象征内存单元、中央处理器单元、主板以及显卡等主要部件的工作状态。例如,若第一个灯亮起,可能指向内存单元存在故障;第二个灯亮,可能是中央处理器单元发生故障。 - 持续闪烁:这种闪烁模式通常指向严重的硬件故障,如自检(POST)过程未能成功完成。 - 快速闪烁:可能意味着BIOS或CMOS设置存在错误。 - 慢速闪烁:可能表明存在次级的硬件问题,如外围设备的连接出现异常。 三、故障排查流程 1. 观察灯码:首先检查电源指示灯,确认系统是否已经正确供电。随后,审视诊断指示灯的闪烁样式,记录下灯码。 2....
内容概要:本文提出了一种结合在线鲁棒主成分分析(RPCA)模型与长短期记忆(LSTM)循环网络的商品需求预测方法,并提供了完整的Python代码实现。该方法首先利用RPCA模型对原始商品需求时间序列进行分解,分离出低秩的潜在趋势成分与稀疏的异常波动成分,有效实现数据去噪与异常值修正,提升输入数据的鲁棒性;随后将净化后的数据输入LSTM网络,充分挖掘时间序列中的长期依赖关系与时序模式,从而提高对未来需求的预测精度。整个模型设计针对实际商业场景中普遍存在的数据噪声大、波动剧烈、突发性事件干扰等问题,展现出较强的稳定性与预测能力。文中通过实验验证了该混合模型在多个指标上优于传统统计模型及单一LSTM模型,体现了其在复杂环境下的优越性能。; 适合人群:具备一定Python编程能力和机器学习基础知识,从事数据分析、供应链管理、电商运营、零售优化及相关领域研究的研发人员或研究生;特别适合关注时间序列预测、深度学习建模以及鲁棒数据处理技术的技术人员。; 使用场景及目标:①应用于电商平台、零售企业或制造行业中的销量预测,以支持库存优化、生产计划制定与物流调度决策;②为科研工作者提供一种融合鲁棒统计与深度学习的预测建模范例,推动高噪声环境下预测算法的创新与复现研究;③帮助开发者深入理解RPCA与LSTM的集成机制,掌握复杂预测模型的构建、训练与调优流程。; 阅读建议:建议读者结合所提供的Python代码逐步实现模型,重点理解RPCA在数据预处理阶段的作用机制以及LSTM网络的结构设计与超参数配置。学习过程中应在真实或模拟数据集上复现实验结果,对比不同参数设置下的模型表现,以深化对模型内在工作原理的理解。同时可进一步探索其他深度学习模型(如GRU、Transformer)与鲁棒分解方法(如VMD、STL)的融合可能性,拓展应用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值