VB.net Learning Notes (28) thread synchronization

Source: Internet
Author: User
Tags mutex


3, ReaderWriterLock class
ReaderWriterLock defines a lock that implements a single-write program and a multi-write program semantics. 4 main methods in the ReaderWriterLock class
? Acquirereacjerlock (): Get-Read program lock, timeout value using an integer or a TimeSpan.
? Acquirewiiterlock (): Gets a write program lock with a timeout value using an integer or a TimeSpan.
? Releasereaderlock (): Release read program lock.
? Releasewriterlock (): Releases the Write program lock.
A thread can hold a reader lock or writer lock, but cannot hold both.

Imports system.threadingnamespace areadwritelock public Class ReadWrite Private RWL as ReaderWriterLock P  Rivate x As Integer Private y As Integer public Sub New () rwl = New ReaderWriterLock () End Sub Public Sub Readints (ByRef A As Integer, ByRef b As Integer) rwl.                AcquireReaderLock (timeout.infinite) Try a = x B = y Finally Rwl.            Releasereaderlock () End Try End Sub public Sub writeints (ByVal A As Integer, ByVal b as Integer) Rwl. AcquireWriterLock (timeout.infinite) Try x = a y = b console.writel INE ("x=" & X & "y=" & Y & "threadid=" & Thread.CurrentThread.GetHashCode.ToString) Final Ly RWL. Releasewriterlock () End Try End Sub End Class public class Rwapp Private RW as New readwrit E PublIC Overloads Shared Sub Main (ByVal args () as String) Dim e As New Rwapp () Dim wt1 As New Thread (new ThreadStart (AddressOf e.write)) wt1. Start () Dim wt2 as New Thread (new ThreadStart (AddressOf e.write)) wt2. Start () Dim Rt1 as New Thread (new ThreadStart (AddressOf e.read)) Rt1. Start () Dim Rt2 as New Thread (new ThreadStart (AddressOf e.read)) Rt2.            Start () Console.ReadLine () End Sub Private Sub Write () Dim A as Integer = 10            Dim B as Integer = one Console.WriteLine ("= = = Write ID:" & Thread.CurrentThread.GetHashCode.ToString) For i as Integer = 0 to 2 rw.  Writeints (A, b) A + = 1 B + 1 thread.sleep (+) Next i End Sub Private Sub Read () Dim A As Integer = ten Dim b As Integer = one Console.writel INE ("= = = Read ID:") & Thread.CurrentThread.GetHashCode.ToString) for I as Integer = 0 to 2 rw. Readints (A, B) Console.WriteLine ("For i=" & I & "A=" & A & "b=" & B & "threadid= "& Thread.CurrentThread.GetHashCode.ToString) Thread.Sleep (+) Next i End Sub E nd classend Namespace
A thread's read lock or write lock can have only one entry at a time, with the following results:


(c) hand-controlled synchronization
Some of the System.Threading namespaces can be used as manual synchronization classes. They give programmers the ability to create and manage multithreaded applications using a low-level threading API similar to the WIN32 threading API. such as: Auto ResetEvent class, ManualResetEvent class, mutex class, interlocked class.
1, ManualResetEvent class
Notifies one or more waiting threads that an event has occurred, depending on the thread that the signal is waiting for to decide whether to continue running down. ManualResetEvent objects can only have two states: signaled (True) or no signal (False).
ManualResetEvent is like a lighthouse beacon that blocks one or more threads until a signal tells ManualResetEvent to stop blocking the current thread.
If there is a signal, the ship all the way unimpeded, the current thread to move forward, even in the face of WaitOne also continue to move;
If there is no signal, the vessel stops at the inattention Reef, and the current thread encounters WaitOne and is blocked.

Imports system.threadingnamespace netthreadevents    Class amanualreset        gkfx lightsign as New ManualResetEvent (False) ' 1, no signal        Shared Sub Main ()            Dim T (4) as Thread for            i as Integer = 0 to 3                t (i) = New Thread (AddressOf Runorwai T)                T (i). Start ()            Next            ' lightsign.set ()                ' 3, resume with signal, thread out of obstruction continues to flow forward run            console.read ()        End Sub        Public Shared Sub runorwait ()            Console.WriteLine ("ID" & Thread.CurrentThread.GetHashCode.ToString & "Waiting ... ")            Lightsign.waitone ()                  ' 2, no signal when the thread hangs blocked, the signal is unblocked            Console.WriteLine (" ID "& Thread.CurrentThread.GetHashCode.ToString & "Running ... not blocked!")        End Sub    End Classend Namespace
Description:Left: 1 is set to false, indicating that the thread was suspended in the event of WaitOne blocking, so the Runorwait () method (2) was suspended at WaitOne. Figure: 1 set to True, thread unblocked, 2 waione directly through. Right: 1 false no signal, so at 2 blocked, but because 3 added a set, let the signal lit, the front of the resumption of the hang, not hang of course also passed. As can be seen in the figure 10-12 thread blocked, since the main thread set recovery signal, the original suspended 11, 12 threads continue to run, as to who grabbed the CPU is determined by the OS.

Note:As to the end and not the end, MSDN:
Original: Reset sets the state of the "event to non-signaled", which causes threads to block. (inherited from EventWaitHandle.)
Reset causes the thread to be blocked by setting the event state to a non-terminating state. (inherited from EventWaitHandle.) )
Because the non-signaled was translated into an unterminated state. Sets the blocked thread to a signal-free event state.

2, AutoResetEvent class
Notifies the waiting thread that an event has occurred. A thread that is in a wait state until it is placed in a signal notification state by calling the set () method.
AutoResetEvent and ManualResetEvent are similar. But there are few differences.
the difference between AutoResetEvent and ManualResetEvent:
(1) AutoResetEvent only sends a signal (not all) to one thread. The ManualResetEvent gives the entire line Cheng signal.
(2) after set () AutoResetEvent, the thread state is automatically reset to False. After the ManualResetEvent is set (), the state of the thread becomes true and the thread must be reset () manually before it is re-set to False.
So ManualResetEvent is like a gate (sign) open (true), all horses (Threads) are running, and the door always turns on True. AutoResetEvent only randomly opens a single door (Set) and shuts down (False) immediately after running (True).
Imports system.threadingnamespace netthreadevents    Class amanualreset        gkfx lightsign as New AutoResetEvent ( False) ' 1, no signal        Shared Sub Main ()            Dim T (4) as Thread for            i as Integer = 0 to 3                t (i) = New Thread (AddressOf R unorwait)                T (i). Start ()            Next            lightsign.set ()     ' 2, randomly releasing a blocked thread (not all)            Console.read ()        End Sub        Public Shared Sub runorwait ()            Console.WriteLine ("ID" & Thread.CurrentThread.GetHashCode.ToString & "Waiting ... ")            Lightsign.waitone ()            Console.WriteLine (" ID "& Thread.CurrentThread.GetHashCode.ToString &" Running ... not blocked! ")        End Sub    End Classend Namespace
Description:Set, only one thread becomes true, so the ID9 thread passes, and ID12 still blocks.


3. Mutex class ( mutex Mutex)
Mutex locks provide cross-threading and cross-sync processes. If no thread has a signaled state, the state of the mutex is set to a signaled state. A mutex does not have all the wait and pulse capabilities of the Monitor class, but it does provide the creation of a named mutex that can be used between processes using overloaded constructors. Using the mutex class is better than the Monitor class: The mutex class can be used across processes, while the Monitor class is not.
The Mutex (Boolean initiallyowned, string name) Initializes a new instance of the mutex class.
initiallyowned:If true, the caller owns the initial ownership of the mutex, otherwise false.
Name:The name of the Mutex. If the value is null, the Mutex is unnamed.
Imports system.threadingnamespace Amutex Class netmutex Private shared Mymutex as Mutex public shared Sub  Main () Mymutex = new Mutex (True, "Magic") Dim nm As New Netmutex Dim t As New Thread (new ThreadStart (AddressOf nm. Run)) T.start () Dim ID as String = Thread.CurrentThread.GetHashCode.ToString Console.writ Eline ("ID:" & ID & "Main thread would sleep for 3 seconds ...") Thread.Sleep (+) CONSOLE.WR            Iteline ("ID:" & ID & "Main thread woke Up") Mymutex.releasemutex () ' 1, release the mutex (get the lock in thread T 3 to run down) Console.WriteLine ("ID:" & ID & "main before WaitOne") Mymutex.waitone () ' 2, block until you get the mutex again (thread t 4 release Lock) Console.WriteLine ("ID:" & ID & "main lock. Owned by Main Thread ') console.readline () End Sub Public Sub Run () Dim ID as String =        Thread.CurrentThread.GetHashCode.ToString    Console.WriteLine ("ID:" & ID & "T_thread in Run Method") Mymutex.waitone () ' 3, block thread t until a mutex is obtained) , after releasing 1 outside, the unobstructed downward Console.WriteLine ("ID:" & ID & "T_thread'll sleep for 6 seconds") THREAD.SL EEP (6000) Console.WriteLine ("ID:" & ID & "T_thread end of Run method") Mymutex.releasemutex () ' 4, the lock must be released here, or 2 will be indefinitely waiting for the lock (last thrown exception) End Sub End Classend Namespace
Description:After the main thread creates the mutex, it holds the lock, waits 3 seconds to release the lock at 1, so that the thread T holds the lock (3) and continues down until the lock (4) is released, the main thread is immediately unlocked and continues to run down at the blocked 2. 4 must be released Cause: MSDN: In. NET on the desktop, if no thread has a mutex, the state of the mutex terminates and the abandonedmutexexception is raised in the next thread that acquires the mutex.


4, intelocked class
The Interlocked class is an atomic operation that provides a method for non-blocking integer updates that are shared among multiple threads. If the variable is in shared memory, the threads of different processes use this mechanism.
Atomic operations, which are indivisible operations, do not switch to another operation when one thread is operating. Can be simply understood as exclusive mode.

Interlocked can provide atomic operations for variables shared by multiple threads:
Interlocked.Increment: Increments the value of the specified variable as an atomic operation and stores the result.
Interlocked.decrement decrements the value of the specified variable in the form of an atomic operation and stores the result.
Interlocked.add in atomic operation, add two integers and replace the first integer with both

Note: The intelocked atomic operation locks a value that is only valid in the three sentences that are similar to the one above, and the atomic operation over this sentence fails.

Imports system.threadingnamespace ainterlocker Class winterlocked public A as New ManualResetEvent (False)            Private I as Integer = 5 public Sub Run (ByVal s as Object) interlocked.increment (i) ' 2, atomic operation incremented            Console.WriteLine (Thread.CurrentThread.GetHashCode.ToString & "" & i) Thread.Sleep (500)  ' Console.WriteLine (Thread.CurrentThread.GetHashCode.ToString & "Completed") ' 3, non-atomic operation End Sub Public  function GetValue () as Integer Return I end Function End Class public class Mainapp public  Shared Sub Main () Dim MR As New ManualResetEvent (False) Dim WL As New winterlocked for I            As Integer = 1 to 10 ' 1, Thread pool queued ThreadPool.QueueUserWorkItem (New waitcallback (AddressOf wl.run), 2)  Next I mr.waitone (+, True) ' Exit the sync domain after 3 seconds Console.WriteLine ("Result of The Times is" &           Wl.getvalue) Console.ReadLine () End Sub End Classend Namespace 
Description:The following two graphs are the above results, especially the left, why there will be two 11, and less 10? First, confirm that 10 threads have entered after atomic operation, each thread is incremented by 1, because 10 threads result in 15 (=5+10), because atomic operation is only at 2, after this sentence is not atomic operation. The details are: a thread atom lock I (=9), then add 1 (i=10), and then exit the atomic operation immediately after the execution of the next sentence to extract the I value (but not yet shown), where the b thread switches in, the atom locks I and adds 1 (i=10+1=11) to I, then the atomic operation exits and extracts I value into the B thread Note that a, B thread extraction of I value is 11, so the display is 11, as for the middle of the 12 is in the output process is to spend time, was another thread C cut in and extract I value 12, and before the B thread output. Add a sentence at 3 to show the result of I, the above effect will be more obvious.


5. Shared variables, methods, and synchronization
Shared variables and methods can be accessed either by the class or by an instance of the class, so the variable or method that synchronizes the lock shared is applied to the entire class. At this point, other objects are not allowed to use shared variables or methods of this class.

      ThreadStaticAttribute class
          A shared variable with ThreadStaticAttribute that has a separate copy of the same variable for each thread that accesses the variable. means that if one thread modifies a variable, another thread that accesses the variable cannot see the changes (including the main thread). This behavior has a default behavior that is back to the shared variable. Useful for example, in a Web application, each request is a separate thread, and if we want to use a value as a static field globally without affecting other users, we usually use the session.

Imports system.threadingnamespace testshared Class athreadstatic <ThreadStatic> public Shared x as Integer ' 1, shared variables, each thread has replica x public shared y as Integer = 1 ' 2, shared variable, each thread has no replica public Sub Run () Fo                R I as Integer = 1 to 5 Dim ID as String = Thread.CurrentThread.GetHashCode.ToString x + = 1 Y + = 1 Console.WriteLine ("I=" & I & "threadid=" & ID & "x=" & X & "y=" & Y) thread.sleep (1000) ' 3. Total 5 cycles, 5 seconds Next I end Sub end Cla  SS Public Class Mainapp Public Shared Sub Main () Dim TS As New Athreadstatic Dim tl As New Thread (new ThreadStart (AddressOf ts.run)) Dim T2 as New Thread (new ThreadStart (AddressOf ts.run)) t L.start () T2. Start () thread.sleep (3500) ' 4, after 3.5 seconds, take a look at the shared variable value in class Console.WriteLine ("Main Thread gET value1: "& athreadstatic.x &" "& Athreadstatic.y) Thread.Sleep (4000) ' 5, 4 Seconds, take a look at the shared variable value in the Class Console.WriteLine ("Main Thread get value2:" & athreadstatic.x & "" & Athreadstatic.y ) Console.ReadLine () End Sub End classend Namespace
Description:X is labeled, each of the two threads will generate a copy of their own x (without affecting the value of the original Class), so at 4 you can see that x is still 0 in the original class, but Y is not labeled, so the value is changed. The final result (5) also shows that X has not been modified to 0 (only the copy is modified in its own thread), and Y is modified to 11.


(iv) Prevention of deadlocks
The more threads, the more complex the lock, the more likely it is to deadlock. The usual principle of prevention is that a thread can have at most one lock.
If you want more locks, you will be more likely to deadlock. For example: A thread has a lock L1 expecting lock L2, whereas a B thread has a lock L2 expecting lock L1, and if two simultaneously occurs or overlaps, a deadlock occurs. Of course, if time is missed, it doesn't matter.
Imports system.threadingnamespace DeadLock Class DL private field_1 as Integer = 0 Private field_2 as Int Eger = 0 Private Lock_1 As Object = new Integer (1) {} Private lock_2 as Object = new Integer (1) {} Pu Blic Sub First (ByVal val as Integer) SyncLock Lock_1 Console.WriteLine ("First:acquired lock_1:" & Thread.CurrentThread.GetHashCode.ToString + "Now Sleeping") thread.sleep (+) Synclo                    CK lock_2 Console.WriteLine ("First:acquired lock_2:" & Thread.CurrentThread.GetHashCode.ToString)        Field_1 = val field_2 = Val End SyncLock End SyncLock End Sub Public Sub second (ByVal Val as Integer) SyncLock lock_2 Console.WriteLine ("Seco Nd:acquired lock_2: "& Thread.CurrentThread.GetHashCode.ToString) SyncLock lock_1 Co Nsole. WriteLine ("Second:Acquired lock I: "& Thread.CurrentThread.GetHashCode (). ToString) Field_1 = val field_2 = Val End SyncLock End Syn            CLock End Sub End Class public class Mainapp Private D as New DL () public Shared Sub Main () Dim m As New Mainapp Dim tl As New Thread (new ThreadStart (AddressOf m.run1)) TL. Start () Dim T2 as New Thread (new ThreadStart (AddressOf m.run2)) T2.        Start () Console.ReadLine () End Sub public Sub Run1 () D.first (ten) End Sub Public Sub Run2 () D.second (ten) End Sub End classend Namespace
Description:Two threads each have a lock, but also look for the direction of the lock, are waiting for each other's lock, so it is dead lock.



VB.net Learning Notes (28) thread synchronization

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.