C# Barrier 实现

C# Barrier 是用于多任务协同工作的同步工具,确保所有任务在进入下一阶段前等待所有其他任务完成当前阶段。它通过SignalAndWait()发送信号,初始化时指定参与者数量和动作。在所有参与者到达后执行指定动作,然后重置并等待新的信号。AddParticipant()和RemoveParticipant()用于动态调整参与者数量。SignalAndWait()方法使用自旋等待和原子操作,当达到预设数量时调用FinishPhase()执行回调函数并释放等待的任务。
摘要由CSDN通过智能技术生成

当您需要一组任务并行地运行一连串的阶段,但是每一个阶段都要等待所有其他任务都完成前一阶段之后才能开始,你一通过Barrier实例来同步这一类协同工作Barrier初始化后,将等待特定数量的信号到来,这个数量在Barrier初始化时指定,在所指定的信号个数已经到来后,Barrier将执行一个指定的动作,这个动作也是在Barrier初始化时指定。Barrier在执行动作过后,将会重置,这时又将等待特定数量的信号到来,再执行指定动作。信号通过成员函数SignalAndWait()来发送,执行SignalAndWait()函数的Task或者线程将会投入等待,Barrier将等待特定数量的信号到达,然后Barrier执行完指定动作后被重置,这时SignalAndWait()函数所在的Task或者线程将继续运行。在程序的运行过程中,可以通过成员函数AddParticipant()和RemoveParticpant()来增加或者减少需要等待的信号数量。让我们来看看Barrier实现:

public class Barrier : IDisposable
{
    // The first 15 bits are for the total count which means the maximum participants for the barrier is about 32K
    // The 16th bit is dummy
    // The next 15th bit for the current
    // And the last highest bit is for the sense
    volatile int m_currentTotalCount;
    const int CURRENT_MASK = 0x7FFF0000;
    const int TOTAL_MASK = 0x00007FFF;
     // Bitmask to extratc the sense flag
    const int SENSE_MASK = unchecked((int)0x80000000);

    // The maximum participants the barrier can operate = 32767 ( 2 power 15 - 1 )
    const int MAX_PARTICIPANTS = TOTAL_MASK;
     long m_currentPhase;
    ManualResetEventSlim m_oddEvent;
    ManualResetEventSlim m_evenEvent;
    ExecutionContext m_ownerThreadContext;
    [SecurityCritical]
    private static ContextCallback s_invokePostPhaseAction;
    Action<Barrier> m_postPhaseAction;
    int m_actionCallerID;
    
    public Barrier(int participantCount): this(participantCount, null) {}
    
    public Barrier(int participantCount, Action<Barrier> postPhaseAction)
    {
        if (participantCount < 0 || participantCount > MAX_PARTICIPANTS)
        {
            throw new ArgumentOutOfRangeException("participantCount", participantCount, SR.GetString(SR.Barrier_ctor_ArgumentOutOfRange));
        }
        m_currentTotalCount = (int)participantCount;
        m_postPhaseAction = postPhaseAction;

        m_oddEvent = new ManualResetEventSlim(true);
        m_evenEvent = new ManualResetEventSlim(false);

        // Capture the context if the post phase action is not null
        if (postPhaseAction != null && !ExecutionContext.IsFlowSuppressed())
        {
            m_ownerThreadContext = ExecutionContext.Capture();
        }
        m_actionCallerID = 0;
    }
    //<returns>The phase number of the barrier in which the new participants will first participate.
    public long AddParticipant()
    {
        try
        {
            return AddParticipants(1);
        }
        catch (ArgumentOutOfRangeException)
        {
            throw new InvalidOperationException(SR.GetString(SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange));
        }
    }
    public long AddParticipants(int participantCount)
    {
        ThrowIfDisposed();
        if (participantCount < 1 )
        {
            throw new ArgumentOutOfRangeException("participantCount", participantCount, SR.GetString(SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange));
        }
        else if (participantCount > MAX_PARTICIPANTS) //overflow
        {
            throw new ArgumentOutOfRangeException("participantCount", SR.GetString(SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange));
        }

        if (m_actionCallerI
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值