Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c# - C#多线程无符号增量(C# multi-threaded unsigned increment)

I want to increment an unsigned integer from multiple threads.

(我想从多个线程增加一个无符号整数。)

I know about Interlocked.Increment, but it does not handle unsigned integers.

(我知道Interlocked.Increment,但是它不处理无符号整数。)

I could use lock(), but I would rather not if possible for performance reasons.

(我可以使用lock(),但出于性能原因,我不希望这样做。)

Is it thread safe just to increment it in the normal way?

(以正常方式递增线程安全吗?)

It would not matter if the occasional increment got lost, as it's only used for statistics.

(偶然的增量是否丢失并不重要,因为它仅用于统计。)

What I don't want is the value to get corrupted.

(我不希望被破坏的价值。)

  ask by FlappySocks translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You say you don't want to use lock for performance reasons - but have you tested it?

(您说出于性能原因不想使用lock -但是您已经测试过了吗?)

An uncontested lock (which this is likely to be, by the sounds of it) is pretty cheap.

(毫无争议的锁(听起来很可能是这样)非常便宜。)

I generally go for "obviously correct" rather than "clever and possibly better performing" when it comes to threading (and in general, but especially for threading).

(在线程方面,我通常选择“明显正确”,而不是“聪明并且可能表现更好”(通常,尤其是对于线程)。)

Benchmark your app with and without locking, and see whether you can even notice the difference.

(使用和不使用锁定对您的应用程序进行基准测试,看看您是否还能注意到其中的区别。)

If locking makes a significant difference then sure, use cunning stuff.

(如果锁定有很大的不同,那么请确保使用狡猾的东西。)

Otherwise, I'd just stick with a lock.

(否则,我只会坚持锁。)

One thing you might want to do is use Interlocked.Increment with an int and just cast it when necessary to get a uint , like this:

(您可能想做的一件事是将Interlocked.Incrementint配合使用,并在需要时将其uint转换为uint ,例如:)

using System;
using System.Reflection;
using System.Threading;

public class Test
{
    private static int count = int.MaxValue-1;

    public static uint IncrementCount()
    {
        int newValue = Interlocked.Increment(ref count);
        return unchecked((uint) newValue);
    }

    public static void Main()
    {
        Console.WriteLine(IncrementCount());
        Console.WriteLine(IncrementCount());
        Console.WriteLine(IncrementCount());
    }

}

Output:

(输出:)

2147483647
2147483648
2147483649

(In other words it wraps with no problems.)

((换句话说,它包装起来没有问题。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...