本文介绍了Interlocked.Increment bug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




是否有与
相关的已知错误
Interlocked.Increment(ref var)?


我的客户报告var'的值在客户端/服务器中上下移动

多线程应用程序。有大约80个客户端连接到一台服务器

虽然是TCP客户端。


但是我从不减少var。


我将其类型更改为volatile int并使用lock来增加其值


lock(this.currentCountLock)

{

this.currentCount ++;

}

并处理我的客户端。 (它在我的机器上永远不会减少)

谢谢,

瑞恩


顺便说一句,为什么volatile不能和ref一起使用?

Hi,

Is there any known bug related to
Interlocked.Increment(ref var)?

My client report var''s value going up and down in the client/server
multile-thread application. There are about 80 clients connect to one server
though TCP client.

But actully I never decrease var.

I change its type to volatile int and use lock to increase its value

lock(this.currentCountLock)
{
this.currentCount ++;
}
and handle over to my client. (It never decreases in my machine)
Thanks,
Ryan

BTW, why volatile can not be used with ref?

推荐答案



你必须给我们更多的背景信息。例如,这段代码:


int ptr = 0;


[thread1]

int x = Interlocked .Increment(ref ptr);

Console.WriteLine(x);


[thread2]

int y = Interlocked。增量(参考资料);

Console.WriteLine(y);


非常乐意打印2,1,看起来好像是'虽然实际上它并没有,并且代码工作正常。

另外,你使用的是Int64版本还是Int32版本?我知道

有一个最近发现的Int64版本的错误

Interlocked.Add。可以想象,Interlocked.Increment(Int64)

可能有同样的错误吗?


-

Lucian

You''ll have to give us a bit more context. For instance, this code:

int ptr=0;

[thread1]
int x = Interlocked.Increment(ref ptr);
Console.WriteLine(x);

[thread2]
int y = Interlocked.Increment(ref ptr);
Console.WriteLine(y);

can quite happily print "2,1", which looks as if it''s decrementing,
even though in reality it isn''t and the code is working fine.
Also, are you using the Int64 version or the Int32 version? I know
there''s a recently-discovered bug in the Int64 version of
Interlocked.Add. It''s conceivable that Interlocked.Increment(Int64)
might have the same bug?

--
Lucian




Ryan,


因为接收方法不知道不稳定的

语义。此外,如果你总是使用锁定,那么就没有必要将
标记为不稳定。


Brian

Ryan,

Because the receiving method would not be aware of the volatile
semantics. Also, if you''re always using a lock then there''s no need to
mark the field as volatile.

Brian



这篇关于Interlocked.Increment bug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 00:17