[C # advanced series] 29 mixed thread synchronization construction,

Source: Internet
Author: User

[C # advanced series] 29 mixed thread synchronization construction,

In the previous chapter, we talked about the primitive thread synchronization structure. Other thread synchronization structures are constructed based on these primitive threads, and are generally combined with the user mode and kernel mode, we call it a hybrid thread synchronization structure.

When there is no thread competition, hybrid threads provide the performance advantages of user mode construction. When multiple threads compete for one construction, hybrid threads provide the advantage of not "Spin" by constructing the primitive kernel mode.

The following is a simple example of mixed thread synchronization construction, which can be compared with the examples at the end of the previous chapter:

Public class SimpleHybridLock: IDisposable {private Int32 m_waiters = 0; private AutoResetEvent m_waiterlock = new AutoResetEvent (false); // note that this is false public void Enter () {if (Interlocked. increment (ref m_waiters) = 1) {return;} m_waiterlock.WaitOne ();} public void Leave () {if (Interlocked. decrement (ref m_waiters) = 0) {return;} m_waiterlock.Set ();} public void Dispose () {m_waiterlock.Dispose ();}}

After learning the above example, it seems very simple and I will not explain it. It is just a simple one that combines Interlocked mutual lock construction and automatic reset event construction AutoResetEvent, example of synchronous construction of mixed threads.

The above mixed locks can be added to spin, and then blocked when the number of spin times exceeds a certain value. You can also add the recursive method of mutex. In short, this thing is full of infinite possibilities.

Hybrid construction in the. NET Framework class library

In general, it is actually an extension of the simple example above. They aim to make the thread do not enter the kernel mode as much as possible, and reduce the performance impact of spin when the thread is competing.

  • ManualResetEventSlim class and SemaphoreSlim class
    • The translation is to manually reset the event to simplify the construction and semaphores to simplify the construction.
    • The kernel mode is constructed only when the first competition occurs. Otherwise, the kernel mode is constructed.
    • The timeout value and CancellationToken can be passed, that is, the token is canceled, and the semaphore can be asynchronously waited.
  • Monitor class and synchronization Block
    • The Monitor class is the most commonly used and supports recursion, thread ownership, and mutual exclusion.
    • However, this class has some problems and is prone to bugs. Because it is a static class, its correct gameplay is somewhat different from other synchronization structures.
    • Each object in the heap can be associated with a data structure called a synchronization block. It is a kernel object and has a thread ID and a recursive count, waiting for the thread count. The operations of the Monitor class involve the fields of these synchronization blocks.
    • Each object has a synchronization block index, and the synchronization block is actually a synchronization block array created during CLR initialization.
    • When an object is constructed, its synchronization block index is-1, that is, it is not associated with any synchronization block. After you call Monitor. Enter, the CLR finds a blank synchronization block in the synchronization block array and sets the synchronization block index of the object so that it can reference the synchronization block. Exit is to cancel the association.
    • Monitor. Enter will pass in an object. This object must be a private object of the class of the function, rather than the object itself. This will make the lock public. This will cause many problems. Therefore, the best way is to pass a private read-only object.
    • Never talk about String. The value type and type object are passed to Monitor. Enter.
    • C # has a simplified syntax provided by the lock keyword, which is based on Monitor. And it is equivalent to using a try finally structure. First, it is not conducive to performance, and second, it may cause thread access corruption. Therefore, we recommend that you do not use the lock syntax.
    • The default value of the LockToken variable is false. It is true only after the Enter call. If you Exit before the Enter call, you can determine the LockToken to avoid incorrect Exit.
  • ReaderWriterLockSlim class
    • Its features:
      • When a thread writes data, all other threads requesting access are blocked.
      • When a thread reads data, other threads requested to read can continue to execute, but the thread writing the request is still blocked.
      • After writing to a thread ends, it can either remove the blocking of a write thread, enable it to write to data, or lift the blocking of all read threads so that they can read data concurrently. If no thread is blocked, the lock enters the usable state, which can be obtained by the next reader or writer thread.
      • After reading data from all threads, a writer thread is blocked so that it can write data. If no thread is blocked, the lock enters the usable state, which can be obtained by the next reader or writer thread.
    • Based on the above features, there are two ways to play EnterReadLock and EnterWriteLock. The two ways are similar to those in the previous examples, but the effect is different. Here we will not give an example.

Although so many synchronization structures are provided, there are also a lot of methods. But the most important thing is to avoid blocking threads as much as possible. Otherwise, the Volatile and Interlocked methods should be used as much as possible because they are fast. However, these two methods can only operate on simple types.

You can use the Monitor class or useReaderWriterLockSlimClass, which is slower than Monitor, but allows concurrent execution of multiple threads, improves overall performance and reduces the chance of blocking threads.

Use the System. Lazy class or the System. Threading. LazyInitializer class to replace the double retrieval method.

Solve this problem in one sentence:

Lazy<String> s=new Lazy<String>(()=>DateTime.Now.ToLongTimeString(),true);

If it is called, s. Value is used. In fact, double search is encapsulated, and some optimizations are added in some places. The purpose is to load data in a delayed manner.

Asynchronous lock

In fact, it is called asynchronous synchronous construction, because the general synchronous construction is completed by blocking threads or spin, and the purpose of asynchronous lock is to play without blocking.

The WaitAsync method of the SemaphoreSlim class is just the method of semaphore.

The reader-writer syntax is the ConcurrentExclusiveSchedulerPair class. (When there is no ConcurrentScheduler task, use ExclusiveScheduler to run it exclusively. When no ExclusiveScheduler is running, the tasks scheduled by ConcurrentScheduler can be executed simultaneously)

Concurrent collection class

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

They are ConcurrentQueue, ConcurrentStack, ComcurrentDictionary, and ConcurrentBag.

All of these are "non-blocking. (In fact, when ConcurrentQueue, ConcurrentStack and ConcurrentBag are empty, the thread that extracts data will be blocked)

 

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.