简体   繁体   English

C#如何使用Interlocked.CompareExchange

[英]C# How to use Interlocked.CompareExchange

My goal is the following: 我的目标是:

There is a certain range of integers, and I have to test every integer in that range for something random. 有一定范围的整数,我必须测试该范围内的每个整数是否具有随机性。 I want to use multiple threads for this, and divide the work equally among the threads using a shared counter. 我想为此使用多个线程,并使用共享计数器在线程之间平均分配工作。 I set the counter at the beginning value, and let every thread take a number, increase it, do some calculations, and return a result. 我将计数器设置为起始值,然后让每个线程取一个数字,将其增加,进行一些计算,然后返回结果。 This shared counter has to be incremented with locks, because otherwise there will be gaps / overlaps in the range of integers to test. 此共享计数器必须使用锁来递增,因为否则将在整数整数范围内进行测试以检测间隔/重叠。

I have no idea where to start. 我不知道从哪里开始。 Let's say I want 12 threads to do the work, I do: 假设我要12个线程来完成工作,我这样做:

for (int t = 0; t < threads; t++)
{
  Thread thr = new Thread(new ThreadStart(startThread));
}

startThread() isthe method I use for the calculations. startThread()是我用于计算的方法。

Can you help me on my way? 您能帮我吗? I know I have to use the Interlocked class, but that's all…. 我知道我必须使用Interlocked类,仅此而已。

Say you have an int field somewhere (initialized to -1 initially) then: 假设您在某处有一个int字段(最初初始化为-1 ),然后:

int newVal = Interlocked.Increment(ref theField);

is a thread-safe increment; 是线程安全的增量; assuming you don't mind the (very small) risk of overflowing the upper int limit, then: 假设您不介意(整数)上限溢出的风险,那么:

int next;
while((next = Interlocked.Increment(ref theField)) <= upperInclusive) {
   // do item with index "next"
}

However, Parallel.For will do all of this a lot more conveniently: 但是, Parallel.For将更方便地完成所有这些操作:

Parallel.For(lowerInclusive, upperExclusive, i => DoWork(i));

or (to constrain to 12 threads): 或(限制为12个线程):

var options = new ParallelOptions { MaxDegreeOfParallelism  = 12 };
Parallel.For(lowerInclusive, upperExclusive, options, i => DoWork(i));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM