"C # Advanced series" 29 hybrid thread synchronization constructs

Source: Internet
Author: User

The previous chapter describes the primitive thread synchronization constructs, while the other thread synchronization constructs are based on these primitive thread synchronization constructs, and generally merge the user mode and kernel schema constructs, we call the hybrid thread synchronous construction.

In the absence of thread contention, the hybrid thread provides the performance benefits that are based on user-mode constructs, while multiple threads compete for a construct, and the hybrid thread provides the advantage of not "spin" through the construction of the primitive kernel mode.

So here's a simple example of a hybrid thread synchronization construct, which can be compared to the last examples from the previous chapter:

      Public classsimplehybridlock:idisposable {PrivateInt32 m_waiters =0; PrivateAutoResetEvent M_waiterlock =NewAutoResetEvent (false);//Note that this is False .         Public voidEnter () {if(Interlocked.Increment (refm_waiters) = =1) {                return; } m_waiterlock.        WaitOne (); }         Public voidLeave () {if(Interlocked.decrement (refm_waiters) = =0) {                return; } m_waiterlock.        Set (); }         Public voidDispose () {M_waiterlock.        Dispose (); }    }

The above example, after learning the previous one, looks very simple and does not explain it, just a simple example of a hybrid thread synchronization construct that combines the interlocked of this interlocking construct with the automatic reset event construction AutoResetEvent.

The above hybrid lock can be added to spin, and then block when a certain number of spins are exceeded. You can also join the recursive gameplay of the mutex, in short this thing is full of infinite possibilities.

Hybrid constructs in the. NET Framework class Library

Overall, it is actually an extension of the simple example above, which is intended to enable threads to be as close as possible to kernel mode and to reduce the performance impact of spin when threading is competing.

  • ManualResetEventSlim class and Semaphoreslim class
    • It's a manual reset event. Simplified construction and signal volume simplification
    • Kernel-mode construction occurs in the first competition, otherwise user-mode constructs
    • The transitive time-out value and the CancellationToken, that is, the cancellation, the semaphore can also be asynchronous waiting.
  • Monitor class and synchronization block
    • The Monitor class is the most common, supporting recursion, thread ownership, and mutex
    • However, there are some problems with this class, which can lead to bugs. Because it is a static class, its correct gameplay is somewhat different from other synchronization constructs.
    • Each object in the heap can be associated with a data structure called a synchronization block, which is a kernel object and has a thread ID, a recursive count, and a waiting thread count. The operation of the Monitor class involves the fields of these synchronization blocks.
    • Each object has a synchronous block index, and the synchronization block is actually a synchronous block array that was created when the CLR was initialized.
    • When an object is constructed, its synchronization block index is-1, that is, there is no synchronization block associated with it. After calling Monitor.Enter, the CLR finds a blank synchronization block in the synchronous block array and sets the object's synchronization block index to refer to the synchronization block. Exit is, of course, a cancellation association.
    • Monitor.Enter will pass an object into the object, which must be the private object of the class of the function, not the object itself, which makes the lock public. This can cause a lot of problems. So the best way is to pass a private read-only object.
    • Never talk about string, value type and type object passed to Monitor.Enter.
    • and C # has a lock keyword that provides a simplified syntax that is based on monitor. And it is equivalent to being used on a try finally structure. First, it is detrimental to performance, and second, it can cause thread access to corrupt state. So the author recommends that the lock syntax be eliminated.
    • The Locktoken variable defaults to False, which is true only after the enter call, and if you exit before the Enter call, you can consider judging Locktoken, thus avoiding the wrong exit.
  • ReaderWriterLockSlim class
    • It is characterized by:
      • When one thread writes to the data, all other threads that request access are blocked
      • When a thread reads from the data, other threads that request read allow the execution to continue, but the thread that requested the write is still blocked.
      • After the thread that writes to the thread ends, either the blocking of a write thread is unblocked so that it can write to the data, or all the read threads are unblocked so that they can read the data concurrently. If no thread is blocked, the lock enters a free-to-use state that can be obtained by the next reader or writer thread.
      • After all threads have been read from the data, a writer thread is unblocked so that it can write to the data. If no thread is blocked, the lock enters a free-to-use state that can be obtained by the next reader or writer thread.
    • According to the above characteristics have enterreadlock and enterwritelock two kinds of play, the two play with the previous examples are similar, but the effect is different, here is not an example.

While there are so many simultaneous constructs available, there are many ways to play them. But the most important thing is to avoid blocking threads as much as possible, or you should use the volatile and interlocked methods as much as possible, because they are fast, but these two can only manipulate simple types.

Be sure to block, you can use the monitor class, or you can use the ReaderWriterLockSlim class, which is slower than monitor, but allows multiple threads to perform concurrently, improving overall performance and reducing the chance of blocking threads.

Use System.lazy class or System.Threading.LazyInitializer class to replace double search play.

A word to solve this point:

lazy<string> s=New lazy<string> (() =>datetime.now.tolongtimestring (),true);

Use S If you invoke the word. Value, in effect, encapsulates a double search, and some places add optimizations. The goal is to delay loading.

Asynchronous lock

In fact, it is called asynchronous synchronous construction, because the general synchronous construction is to use blocking thread or spin to complete, and the purpose of the asynchronous lock is to do not block to play.

The Waitasync method of Semaphoreslim class is this idea, the semaphore play only.

And Reader-writer semantics is the Concurrentexclusiveschedulerpair class. (when there is no Concurrentscheduler task, use Exclusivescheduler to run exclusively.) Concurrentscheduler Scheduled tasks can be performed simultaneously without Exclusivescheduler runtime)

Concurrent collection Classes

The FCL comes with four thread-safe collection classes, all defined in the System.Collections.Concurrent (Concurrent for concurrency meaning) namespace.

They are concurrentqueue,concurrentstack,comcurrentdictionary and concurrentbag.

All of these are "non-blocking". (actually extract the data when Concurrentqueue,concurrentstack and Concurrentbag are empty, then the thread that pulls the data is blocked)

C # Advanced series 29 hybrid thread synchronization constructs

Related Article

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.