One, why do threads need to be synchronized
It is possible for threads to share some resources with other threads, such as memory, files, databases, and so on.
Conflicts can arise when multiple threads read and write to the same shared resource at the same time. At this time, we need to introduce the thread "synchronization" mechanism, that is, there is a first served between the threads, you can not swarm squeeze up to grab a regiment.
The true meaning and literal meaning of thread synchronization is exactly the opposite. The true meaning of thread synchronization is actually "queued": there are several threads to queue, one to operate on shared resources, and not to operate concurrently.
Second, the common thread synchronization mechanism.
1. Maintenance free Lock (interlocked) for synchronization
2. Monitor andmutex (lock)
3. Read/write Lock (readwritelock)
4. System Kernel Objects
1) Mutex (mutex), Semaphore (Semaphore), event (autoresetevent/ManualResetEvent)
2) thread pool
5.Thread.Join method. This method is relatively simple, when you want to wait for the second thread to execute the result when the first thread is running, then you can let the second thread join in.
1.1 Free Lock (interlocked)---provides atomic operations for variables shared by multiple threads. This class provides the add, Increment, and decrement to perform simple atomic operations
Using + + or--to manipulate threads is unsafe.
2.1 The most common is the mutex (lock), but the performance impact is relatively large.
Private list<string> accountlist; Shared objects
Try
{
Waiting for thread to enter
Monitor.Enter (accountlist);
Names.remove ("Feige");
Console.WriteLine ("Del: {0}", Accountlist.count);
Monitor.pulse (accountlist);
}
Finally
{
Releasing Object locks
Monitor.Exit (accountlist);
}
3.1 Read/write lock readwritelock
We read resources more than the write resource operation. But it's obviously inefficient to give one thread access to a resource at a time.
Advantage: It is possible for multiple threads to read the same resource at the same time. Therefore, it is more efficient to use a read-write lock when the read operation is much more than the write operation and the time for the write operation is very short.
A read-write lock is a non-static class so you need to declare a read-write lock object before you use it:
private static ReaderWriterLock feigelock= new ReaderWriterLock ();
Feigelock. AcquireReaderLock (1000); Request read lock in 1 seconds
Try
{
int inx = _rand. Next (_list. Count); if (Inx < _list. Count)
Console.WriteLine ("{0}thread {1}", Thrdid, _list[inx]);
}
finally{ feigelock. Releasereaderlock (); Release the read-write lock
Understanding Thread Synchronization