使用局部静态变量线程安全/可重入的函数 [英] Function using a local static variable thread safe/reentrant

查看:269
本文介绍了使用局部静态变量线程安全/可重入的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以为调用它的不同线程生成一个唯一的随机数(基本上在前面递增).

I have a function that will generate a unique random number(basically increment previous) to different threads invoking it.

此线程安全还是可重入.假设我为此数字使用了静态变量.

Is this thread safe or is this reentrant.Assume I used static variable for this number.

我在这个论坛上看到静态变量不能用于可重入/线程安全.

I have seen in this forum static variables cant be used for reentrant/thread safe.

它是否适用于本地/全局静态.

Does it applies for local/global static.

还是定义了实现?

推荐答案

更改线程之间共享的普通"对象绝不是线程安全的,除非您特别注意. (并且任何静态声明的变量都属于该类别).有两种标准的处理方法

Changing an "ordinary" object that is shared between threads is never thread safe, unless you take special care of it. (and any statically declared variable falls in that category). There are two standard ways of dealing with that

  • 使用互斥锁或其他锁定结构来保护关键部分"内的共享对象
  • 使用原子操作访问对象,新的C标准C11为此提供了接口

要成为可重入者询问执行(即使没有线程)是否可以修改部分状态,例如递归,信号处理程序或使用gotolongjmp跳转.将其视为与您自己"共享变量.如果您在程序的不同位置进行修改,则静态分配的变量会在此处产生相同的问题.

Being reentrant asks if an execution (even without threads) can modify part of the state, examples are recursion, signal handlers or jumps with goto or longjmp. Think of it as sharing a variable with "yourself". Statically allocated variables make the same problems here, if you modify them from different places of the program.

这篇关于使用局部静态变量线程安全/可重入的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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