ID生成器与本地静态变量 - 线程安全? [英] ID generator with local static variable - thread-safe?

查看:128
本文介绍了ID生成器与本地静态变量 - 线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在多线程方案中如预期工作?

  int getUniqueID()
{
static int ID = 0;
return ++ ID;
}

ID不必是连续的 - 即使它跳过一个值, 没关系。
可以说,当这个函数返回时,返回的值将在所有线程中是唯一的。

解决方案

否,它不会。您的处理器将需要执行以下步骤来执行此代码:




  • 从内存中获取ID值到寄存器

  • 增加寄存器中的值

  • 将增加的值存储到内存中



如果在此(非原子)序列期间发生线程切换,则可能发生以下情况:




  • 线程a将值1提取到

  • 线程a递增此值,因此寄存器现在包含2

  • 获取值1(仍在内存中)

  • 上下文切换

  • 将商店2分配给记忆并返回

  • 上下文切换

  • 线程b将其寄存器中存储的值增加到2

  • 线程b到内存并返回2



$ b

Will the following piece of code work as expected in a multi-threaded scenario?

int getUniqueID()  
{  
    static int ID=0;  
    return ++ID;  
}

It's not necessary that the IDs to be contiguous - even if it skips a value, it's fine. Can it be said that when this function returns, the value returned will be unique across all threads?

解决方案

No, it won't. Your processor will need to do the following steps to execute this code:

  • Fetch value of ID from memory to a register
  • Increment the value in the register
  • Store the incremented value to memory

If a thread switch occurs during this (non atomic) sequence, the following can happen:

  • Thread a fetches the value 1 to a register
  • Thread a increments the value, so the register now contains 2
  • Context switch
  • Thread b fetches the value 1 (which is still in memory)
  • Context switch
  • Thread a stores 2 to memory and returns
  • Context switch
  • Thread b increments the value it has stored in its register to 2
  • Thread b (also) stores the value 2 to memory and returns 2

So, both threads return 2.

这篇关于ID生成器与本地静态变量 - 线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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