gpt4 book ai didi

c++ - 如何在源代码中强制执行单线程构建

转载 作者:可可西里 更新时间:2023-11-01 17:55:32 26 4
gpt4 key购买 nike

背景:我为一些非常专业的数据处理创建了许多小型实用程序。通常,我是唯一的用户。我什至不考虑多线程编程,因为运行时性能对于我的用例来说已经足够了。关键资源是我的编程时间。所以我想避免多线程编程所需的任何额外工作。

但是,当我将来重用我的代码时,似乎存在一个风险,即我的源代码会在多线程上下文中执行。

根据 CppCoreGuidelines :

Be careful: there are many examples where code that was “known” to never run in a multi-threaded program was run as part of a multi-threaded program. Often years later. Typically, such programs lead to a painful effort to remove data races. Therefore, code that is never intended to run in a multi-threaded environment should be clearly labeled as such and ideally come with compile or run-time enforcement mechanisms to catch those usage bugs early.

同一来源中的大多数建议实际上让我开始了多线程编程。我更愿意遵循的一个建议是:

Refuse to build and/or run in a multi-threaded environment.

所以我的问题是,我该怎么做?例如。是否有包含文件、#pragma 等来确保源文件中所有内容的单线程构建/执行?

最佳答案

g++/gcc编译和链接多线程代码需要使用 -pthread编译器和链接器选项。此选项设置 _REENTRANT您可以在编译时检查的宏:

$ c="g++ -E -dD -xc++ /dev/null"
$ diff <($c) <($c -pthread)
389a390
> #define _REENTRANT 1

与流行的看法相反,using -lpthread linker option is unnecessary and insufficient to correctly build a multi-threaded program .


Microsoft Visual Studio 集 _MT用于多线程构建的宏,IIRC。


Boost 库执行以下操作:

// Turn on threading support if the compiler thinks that it's in
// multithreaded mode. We put this here because there are only a
// limited number of macros that identify this (if there's any missing
// from here then add to the appropriate compiler section):
//
#if (defined(__MT__) || defined(_MT) || defined(_REENTRANT) \
|| defined(_PTHREADS) || defined(__APPLE__) || defined(__DragonFly__)) \
&& !defined(BOOST_HAS_THREADS)
# define BOOST_HAS_THREADS
#endif

这样你就可以#include <boost/config.hpp>然后检查 BOOST_HAS_THREADS 的值宏。


如果在多线程模式下构建,下面会导致编译错误:

#if defined(BOOST_HAS_THREADS) || defined(_REENTRANT) || defined(_MT)
#error This code is single-threaded only.
#endif

关于c++ - 如何在源代码中强制执行单线程构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49997217/

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