线程安全替换代码? [英] Thread-safe replace for code?

查看:81
本文介绍了线程安全替换代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发过程中,我经常遇到下一个问题:如果某个方法已经由一个线程执行-方法一定不能由另一个线程执行.另一个线程什么也不做-从方法简单退出,因为我不能使用锁".通常,我会这样解决这个问题:

In process of developing I often face with the next problem: if some method is already executed by one thread - method is must not be executed by another thread. Another thread must do nothing - simple exit from method, beacuse of it I can't use "lock". Usually, I solve this problem like that:

private bool _isSomeMethodExecuted = false;

public void SomeMethod ()
{
 if (!this._isSomeMethodExecuted) //check if method is already executed
 {
        this._isSomeMethodExecuted = true;

        //Main code of method

        this._isSomeMethodExecuted = false;
 }
}

但是此代码不是线程安全的:如果一个线程执行条件语句,但是在set标志为true之前停止并且另一个线程可以执行条件-那么两个线程都在方法代码内部.

But this code is not thread-safe: if one thread execute condition statement but It be stopped before set flag in true and another thread can execute condition - then both threads are inside method code.

是否有任何线程安全的替代品?

Is there any thread-safe replace for it?

推荐答案

以下内容是线程安全的,并且即使该方法已在执行也不会阻塞-即使在同一线程上执行也很容易...这提供了保护在所有情况下都可以重新进入.

the following is thread-safe and does not block if the method is already executing - even if it is alreasy executing on the same thread... which provides protection from reentrancy for all scenarios.

private long _isSomeMethodExecuted = 0;

public void SomeMethod ()
{
 if (Interlocked.Increment (ref this._isSomeMethodExecuted) == 1) //check if method is already executed
 {
        //Main code of method

 }
Interlocked.Decrement (ref this._isSomeMethodExecuted);
}

有关参考,请参见 http://msdn.microsoft.com/zh-CN /library/zs86dyzy.aspx

这篇关于线程安全替换代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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