线程安全和租金 [英] Thread Safe and Rentrancy

查看:68
本文介绍了线程安全和租金的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多地方都读到,线程安全函数总是可重入的,但是可重入函数并不总是线程安全的.

我了解第二部分,可重入函数并不总是线程安全的,因为可重入函数对每个线程的本地数据都起作用,因此,如果可重入函数正在访问其中的任何全局数据,那么它就不能是线程安全的. br/>
但是有人能举例说明线程安全函数如何总是可重入的吗?

I have read at many places that a thread-safe function is always reentrant, but a reentrant function is not always thread-safe.

I understand the second part that reentrant function is not always thread-safe, since the reentrant function works on each of the thread''s local data and so if the reentrant function is accessing any global data in it then it cannot be threadsafe.

But will anybody explain with example how can a threadsafe function be always reentrant?

推荐答案

线程安全函数总是可重入的,因为否则它根本就不是线程安全的完全没有.如果您有一个不加锁定地读取/更改全局变量的函数,则两次调用此函数(从另一个线程同时调用或在某个时候递归调用)可能会产生意外的结果.每次全局值都可能以不受控制的方式更改.

线程安全功能通过锁定共享资源,然后在本地复制所需的数据来防止更改生效.正确实施后,此数据现在属于该线程,并且不依赖于全局共享资源.

递归函数也是如此.他们可以简单地将全局值复制到局部变量,这意味着递归调用可以更改全局数据,但不能更改递归链中较早方法的本地存储数据.但是要注意的是,只有一次由单个线程调用此函数时,此方法才起作用.如果多个线程将使用此递归机制,那么它不仅是对同一函数的顺序调用链,而且还可以由不同的线程调用.然后,将全局数据复制到本地数据将需要锁定以防止意外行为.

因此,线程安全函数可以安全地用于递归中(如果这样做时它没有挂在锁上),而递归函数本身根本就不是线程安全的.

祝你好运!
A thread safe function is always reentrant because otherwise it simply wouldn''t be thread safe at all. If you have a function that reads/changes a global variable without locking, then calling this function twice (at the same time from another thread or recursively at some point) might have unexpected results. Each time the global value might change in an uncontrolled way.

A thread safe function prevents that changes have effect by locking shared resources and then copying the needed data locally. Implemented correctly, this data now belongs to that thread and is not depending on globally shared resources.

The same goes for recursive functions. They can simply copy a global value to a local variable, meaning that a recursive call could change the global data but not the locally stored data of a method earlier in the chain of recursion. But the catch is that this will only work if this function is called by a single thread at a time. If multiple threads would use this recursive mechanism then it isn''t just a sequential chain of calls to the same function, but can also be called by different threads. Copying global data to local data would then need locking to prevent unexpected behavior.

Therefor a thread safe function can be safely used in recursion (if it doesn''t hang on to a lock when doing so) while a recursive function by itself isn''t thread safe at all.

Good luck!


这篇关于线程安全和租金的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆