Ruby线程局部变量
自版本2.0以来,Ruby对线程局部变量具有本机支持。然而,active_support/core_ext/thread.rb在纯ruby中实现了此功能,以支持ruby早期版本中的线程局部变量。所以,我想知道为什么我们应该在\u locals方法中使用互斥:Ruby线程局部变量,ruby,multithreading,mutex,activesupport,Ruby,Multithreading,Mutex,Activesupport,自版本2.0以来,Ruby对线程局部变量具有本机支持。然而,active_support/core_ext/thread.rb在纯ruby中实现了此功能,以支持ruby早期版本中的线程局部变量。所以,我想知道为什么我们应该在\u locals方法中使用互斥: \u locals做两件事: def _locals # 1. Returns the local variable hash when defined if defined?(@_locals) @_locals #
\u locals
做两件事:
def _locals
# 1. Returns the local variable hash when defined
if defined?(@_locals)
@_locals
# 2. Lazily instantiates a locals hash
else
LOCK.synchronize { @_locals ||= {} }
end
end
需要同步步骤以确保在首次访问期间不会清除@\u locals
考虑以下场景:
thread = Thread.new
# Say I run this statement...
thread.thread_variable_set('a', 1)
# In parallel with this statement...
thread.thread_variable_get(:a)
这两种方法都调用\u locals
,如果它们同时执行,它们可能都会在延迟分配步骤结束:
@_locals ||= {}
# Expands to...
unless @_locals
@_locals = {} # <-- We could end up here with both threads at the same time,
end # which jeopardizes any value that might have been set.
我明白你的话。但我的问题是关于在active_support/core_ext/thread.rb中使用互斥锁。如何在特定线程上运行并行读写访问?我们讨论与特定线程相关的局部变量。线程可能相互作用,或者某个更高的进程可能在线程运行时与线程相互作用。这提供了一层保护,防止在这些情况下发生碰撞。好的。那么为什么线程变量集中没有互斥同步块呢?这是程序员的选择。
unless Thread.instance_methods.include?(:thread_variable_set)