c++ - VC++ 中的光纤安全优化到底是什么?

标签 c++ arrays multithreading visual-c++ optimization

我正在阅读 Fiber Safe optimizations在 MSDN 上。据说

Data declared with __declspec(thread) is referenced through a thread-local storage (TLS) array. The TLS array is an array of addresses that the system maintains for each thread. Each address in this array gives the location of thread-local storage data. A fiber is a lightweight object that consists of a stack and a register context and can be scheduled on various threads. A fiber can run on any thread. Because a fiber may get swapped out and restarted later on a different thread, the address of the TLS array must not be cached or optimized as a common sub expression across a function call

什么是光纤安全优化?使用它的实际目的是什么?为什么他们说“因为光纤可能会被换出并稍后在不同的线程上重新启动,所以 TLS 数组的地址不得缓存或优化为跨函数调用的公共(public)子表达式。”?为什么以及何时应该阻止它?

最佳答案

Fiber(在此上下文中)是一种 MS 特定技术,可让您手动控制“轻量级”工作线程的调度,但它们与线程共存。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms682661(v=vs.85).aspx

假设您有一个 fiber 有很长的工作要做,还有两个工作线程。

纤程在一个线程上运行并被取消调度。然后下一个线程 获得处理器时间。它发现纤程需要运行,所以它运行纤程。

到目前为止,没有问题。除非您使用的是线程本地存储。

__declspec(thread) int global_int;

您创建的每个线程 都会看到该变量的它自己的唯一实例。如果您的纤程代码使用这样的变量并且您允许纤程在线程之间转换,那么底层变量可能会改变。当然,其中最明显的是 thread id

void fiber_in_your_diet() {
    Queue& thread_queue = g_threadQueues[std::thread::get_id()];
    // long work that gets transferred to a different thread
    thread_queue.push_back(something); // wrong queue!
}

“光纤安全优化”用词不当。如果您正在使用 Fibers 并且您很可能没有使用,那么您只需要“/GT”。如果你是,你就会知道,部分原因是你早上醒来时对生活的强烈仇恨,部分原因是你会知道纤维是什么。

--- 编辑 ---

“Fiber”相当广泛地用于描述一个“轻量级”执行单元,它没有操作系统线程的花哨功能,特别是它不会自动运行。根据您的要求,纤维实际上可能比线更便宜。它们通常与协程相关联(参见 https://en.wikipedia.org/wiki/Fiber_(computer_science)#Fibers_and_coroutines )。请注意,C++ 语言的 future 版本可能包含 Fiber 概念的标准实现(参见 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4024.pdf)

关于c++ - VC++ 中的光纤安全优化到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042684/

相关文章:

c++ - 无法找到过程入口点 __gxx_personality_v0

c++ - zip 文件可以是稀疏的/不连续的吗?

javascript - 如何将我的 json 数据加载到 html 表中并使用纯 Javascript 将行设置为单选按钮?

c++ - boost::thread vs std::thread vs pthread

python - 如何清除 Python threading.local 对象?

c++ - 使用可变修改类型实例化模板

c++ - defines/macros/structs 和 consts/funcs/classes 在使用方面有什么区别? (C++)

javascript - 将特定数组值合并为单个值

python:替换从文件读取的数组中的负值

java - 在队列中等待的线程,Java