采用互锁用法 [英] using interlocked usage

查看:235
本文介绍了采用互锁用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个多线程程序,每个线程将使用一个计数器,然后增加它

I am trying to write a multithreaded program where each thread would use a counter and then increment it.

例如:

lock(this)
{
   counter++;
   Console.WriteLine(counter); 
}



我知道,对于增量,我可以使用:

i know that for incrementation i can use:

System.Threading.Interlocked.Increment(counter);



但如何锁定为递增和做一些与计数器?

but what about locking for both incrementing and doing something with the counter?

感谢

推荐答案

这样做是OK!

线程A:

var incremented_counter = Interlocked.Increment(ref counter);
Console.WriteLine(incremented_counter);



线程B:

Interlocked.Increment(ref counter);






和这样做是确定:


And doing this is OK:

线程A:

lock (the_lock) {
   ++counter;
   Console.WriteLine(counter); 
}



线程B:

lock (the_lock) {
   ++counter;
}






这样做,这是确定的,但的冗余的:

线程A:

lock (the_lock) {
    var incremented_counter = Interlocked.Increment(ref counter);
    Console.WriteLine(incremented_counter);
}



线程B:

lock (the_lock) {
    Interlocked.Increment(ref counter);
}






不过,这样做是的确定:

线程A:

Interlocked.Increment(ref counter);
Console.WriteLine(counter);



线程B:

Interlocked.Increment(ref counter);






也不是这样做的:


Nor is it doing this:

线程A:

lock (the_lock) {
   ++counter;
   Console.WriteLine(counter); 
}



线程B:

Interlocked.Increment(ref counter);






也不是这样做的:


Nor is it doing this:

线程A:

var incremented_counter = Interlocked.Increment(ref counter);
Console.WriteLine(incremented_counter);



线程B:

lock (the_lock) {
   ++counter;
}

(顺便说一句,的不使用锁定这个 。)

这篇关于采用互锁用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆