我使用AtomicReference来实现AtomicInteger.然而,在测试中,我注意到即使在单线程环境中,一旦其值达到128,CAS操作就会卡住.我做错了什么或在AtomicReference中有一个警告(可能与CPU有关)?这是我的代码:
public class MyAtomInt {
private final AtomicReference<Integer> ref;
public MyAtomInt(int init) {
ref = new AtomicReference<Integer>(init);
}
public MyAtomInt() {
this(0);
}
public void inc() {
while (true) {
int oldVal = ref.get();
int nextVal = oldVal + 1;
boolean success = ref.compareAndSet(oldVal, nextVal); // false once oldVal = 128
if (success) {
return;
}
}
}
public int get() {
return ref.get();
}
static class Task implements Runnable {
private final MyAtomInt myAtomInt;
private final int incCount;
public …Run Code Online (Sandbox Code Playgroud) 当我试图分离非成员重载运算符的声明和实现时,我在VC2010中遇到LNK2001错误,我的代码是这样的:
-foo.h-
class A
{
public:
A(float x);
float x;
};
A operator +(const A&, const A&);
Run Code Online (Sandbox Code Playgroud)
-foo.cpp-
A::A(float x)
{
this->x = x;
}
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
Run Code Online (Sandbox Code Playgroud)
所以一旦我使用'+'操作,错误泵出,但如果我删除头文件中的声明,没有LNK2001错误..我无法弄清楚为什么..
以下代码有什么问题:
class A
{
public:
static A* p;
A()
{
p = this;
}
};
Run Code Online (Sandbox Code Playgroud)
我收到此链接错误:
错误LNK2001:未解析的外部符号"public:static class A*A :: p"(?p @ A @@ 2PAV1 @ A)
我无法弄清楚这个问题的重点,请帮忙..