gpt4 book ai didi

c - 当线程在 c 中调用 longjmp() 时会发生什么

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:06 25 4
gpt4 key购买 nike

当你有一个用c语言调用longjmp的线程时会发生什么。我知道当一个程序在单线程上时,PC 被放回创建 jmp_buf 时的地址,并且处理器的寄存器恢复到那个时间点。

  1. 如果在线程内调用setjmp,然后调用longjmp,是否一切正常?
  2. 如果在任何线程存在之前调用 setjmp,然后一个线程在那个 jmp_buf 上调用 longjmp,它会杀死所有其他线程吗因为在创建 jmp_buf 时它们不存在?

最佳答案

相关函数的 POSIX 规范可在以下位置找到:

请注意,longjmp() 的规范列出了一些限制:

The longjmp() function shall restore the environment saved by the most recent invocation of setjmp() in the same process, with the corresponding jmp_buf argument. If the most recent invocation of setjmp() with the corresponding jmp_buf occurred in another thread, or if there is no such invocation, or if the function containing the invocation of setjmp() has terminated execution in the interim, or if the invocation of setjmp() was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined. [CX] ⌦ It is unspecified whether longjmp() restores the signal mask, leaves the signal mask unchanged, or restores it to its value at the time setjmp() was called. ⌫

对于您的场景:

  1. 应该没问题。
  2. 未定义的行为。相反,如果主线程(或调用 setjmp() 的线程)执行 longjmp(),它应该没问题,但它不会杀死其他线程。即使这样,您也可能会违反 longjmp() 的一般限制。

总的来说,要明智且非常保守。它们是脆弱的功能。除非真的有必要,否则不要使用它们,并担心一般的资源管理。

关于c - 当线程在 c 中调用 longjmp() 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56485386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com