简体   繁体   English

如何以线程安全的方式退出C ++ 03中的程序?

[英]How to exit a program in C++03 in a thread-safe manner?

I have a multi-threaded C++03 application (Linux-based) that I want to terminate immediately in a thread-safe manner. 我有一个多线程C ++ 03应用程序(基于Linux),我想立即以线程安全的方式终止。

I have tried using exit(0) but this destroys some static variables which are actively being used by another thread, causing that thread to access freed memory and destroyed objects, resulting in a core dump! 我已经尝试使用exit(0),但是这会破坏一些静态变量,这些变量正在被另一个线程主动使用,导致该线程访问释放的内存并销毁对象,从而导致核心转储! Apparently the exit() function has a data race: "Calling this function destroys all objects with static duration: A program with multiple threads running shall not call exit (see quick_exit for a similar function that does not affect static objects)." 显然,exit()函数有一个数据竞争:“调用此函数会破坏具有静态持续时间的所有对象:运行多个线程的程序不应调用exit(有关不影响静态对象的类似函数,请参阅quick_exit)。”

C++11 offers a thread-safe quick_exit() function. C ++ 11提供了一个线程安全的quick_exit()函数。 But I don't have the ability to move this large application to C++11 at the moment. 但我现在无法将这个大型应用程序移动到C ++ 11。

I also don't want to spend effort trying to do clean termination/joining of threads. 我也不想花费精力尝试干净终止/加入线程。 This is a very complex program and that would take a considerable amount of work. 这是一个非常复杂的计划,需要相当多的工作。

Are there any other alternatives? 还有其他选择吗? I just want the program to exit immediately, no cleanup, no core dump. 我只是想让程序立即退出,没有清理,没有核心转储。

Edit: What I'm really trying to do is replace abort() calls with something that won't create a coredump. 编辑:我真正想要做的是用不会创建coredump的东西替换abort()调用。 And abort() is thread-safe, btw. 而abort()是线程安全的,顺便说一句。

You will get the effect you want by calling _exit(status) (note the leading underscore) 您将通过调用_exit(status)获得所需的效果(请注意前导下划线)

documentation: 文档:

http://man7.org/linux/man-pages/man2/_exit.2.html http://man7.org/linux/man-pages/man2/_exit.2.html

It is not clear what you want to terminate: process or thread. 目前尚不清楚你想要终止什么:进程或线程。 It's usually safe to terminate a process and return control to OS but terminating a thread by "brute force" is usually a bad idea. 终止进程并将控制权返回给操作系统通常是安全的,但通过“强力”终止线程通常是一个坏主意。 The reason is many code and library are written with the assumption of being running in a single threaded environment. 原因是许多代码和库都是在假设在单线程环境中运行的情况下编写的。 Killing a thread WILL leave some global variables in a "quantum state", which will cause problems for the code running in other threads. 杀死一个线程会使一些全局变量处于“量子状态”,这将导致在其他线程中运行的代码出现问题。 It's better to pay your effort to find some place in the said code and politely "ask" it exit. 最好付出努力在上述代码中找到一些地方并礼貌地“问”它退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM