The C #2.0 implementation of the lightweight lock free thread-safe queue

Source: Internet
Author: User

Recently, some C #2.0Code... Discover unsafe implementations of various threads

No concurrentcollection classes in 2.0

As a last resort, I wrote one myself,

Originally intended to use the traditional lock implementation, but considering that the operation is very lightweight... Eventually still uses the lock free

Use interlocked to replace common lock keywords.

     Public   Sealed   Class Safedqueue <t>
{
# Region Private Fields
Private Int Istaked = 0 ;
Private Queue <t> queue =New Queue <t> ();
Private Int Maxcount = 1000 * 1000 ;
# Endregion

Public Void Enqueue (T)
{
Try
{
While (Interlocked. Exchange ( Ref Istaked,1 )! = 0 )
{
}
This . Queue. enqueue (t );
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}

Public T dequeue ()
{
Try
{
While (Interlocked. Exchange ( Ref Istaked, 1 )! = 0 )
{
}
T = This . Queue. dequeue ();
Return T;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}

Public Bool Tryenqueue (T)
{
Try
{
For ( Int I = 0 ; I <maxcount; I ++)
{
If (Interlocked. Exchange ( Ref Istaked, 1 ) = 0 )
{
This . Queue. enqueue (t );
Return True ;
}
}
Return False ;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}

Public Bool Trydequeue ( Out T)
{
Try
{
For ( Int I = 0 ; I <maxcount; I ++)
{
If (Interlocked. Exchange ( Ref Istaked, 1 ) = 0 )
{
T = This . Queue. dequeue ();
Return True ;
}
}
T = Default (T );
Return False ;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}
}

Methods Starting with try have a limit on the number of attempts. If the limit is exceeded, the system exits and returns false.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.