静态局部变量的线程安全增量 [英] Thread safe increment of static local variable
问题描述
void foo() {
static int id = 0;
const int local_id = id++;
//do something with local_id;
}
多个线程可以并行调用foo多次.我希望对foo的每个调用都使用local_id的唯一"值.上面的代码可以吗?我想知道第二个线程是否在第一个线程增加id的值之前将其值分配给local_id.如果不安全,是否有任何标准解决方案?
Multiple threads can call foo in parallel multiple times. I want each call of foo use "unique" value of local_id. Is it ok with the above code? I wonder if second thread assign the value of id to local_id before the value is increased by the first thread. If it is not safe, is there any standard solution for this?
推荐答案
您的代码不是线程安全的,因为多个线程可以同时读取id
并产生相同的local_id
值.
Your code is not thread-safe, because multiple threads can read id
concurrently, and producing the same value of local_id
.
如果要使用线程安全版本,请使用std::atomic_int
,它在C ++ 11中可用:
If you want a thread-safe version, use std::atomic_int
, which is available in C++11:
void foo() {
static std::atomic_int id;
const int local_id = id++;
//do something with local_id;
}
这篇关于静态局部变量的线程安全增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!