我感到困惑的C++ 11的原子操作,当增加原子变量并将其赋值给其他值时,C++ 11是原子操作吗?
我知道原子变量自我增值是原子操作,
,但我用的是分配给其他值,只是怀疑。
代码就像:
//....
static std::atomic<int> i; // global variable
//....
// in the thread
int id = ++i;
使用在不同的线程分配的情况下
,是id独特的价值?
测试代码:
#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>
class A {
public:
static int idGenerator;
static std::mutex m;
A() {
// i know this operation will keep the id_ is unique
std::lock_guard<std::mutex> lock(m);
id_ = ++idGenerator;
}
void F(std::string name) {
std::cout << name << " " << id_ << std::endl;
}
private:
int id_;
};
int A::idGenerator = 0;
std::mutex A::m;
class B {
public:
static int idGenerator;
B() {
// after self increment, is the assignment atomic?
id_ = (++idGenerator);
}
void F(std::string name) {
std::cout << name << " " << id_.load() << std::endl;
}
private:
std::atomic<int> id_;
};
int B::idGenerator = 0;
void funcA() {
A a2;
a2.F("a2");
}
void funcB() {
B b2;
b2.F("b2");
}
int main() {
A a1;
B b1;
std::thread t1(&funcA);
std::thread t2(&funcB);
a1.F("a1");
b1.F("b1");
t1.join();
t2.join();
return 0;
}
有三个线程,
类使用lock_guard保持独特。
B级只使用原子操作,并赋给变量
参见API'的std ::原子:: fetch_add'覆盖在原子单元的两个操作。 – 2014-09-03 04:40:31
对原子变量(或增量操作)的赋值是很原子的。对任何其他变量的赋值不保证是原子的。但是,为了使其“线程安全”,在并发访问的所有场景中,单独使用原子性是不够的。此外,在'B'类看你的代码,看起来你想让静态成员变量idGenerator原子,而不是成员变量'id_'。 – CouchDeveloper 2014-09-03 05:46:59
我读了crtmpserver代码,并且每个连接只有一个iohandler类,iohandler的id由静态的generateId生成。 crtmpserver是Single Process,如果我尝试添加多线程支持,那么id应该保持与前面一样 – 2014-09-03 08:37:17