About Thread Synchronization

Source: Internet
Author: User
Tags reflector
I wrote a post last time to record some gains on Asynchronous calling in UI development. The reason why I used asynchronous calling is that I need to enable a working thread to do something, and ensure thread security. After the problem is solved, I started to find some thread synchronization problems in the blog of an expert friend of mine, SDK, msdn, and I read some things, I also wrote some things and tested them myself, but I still understood some of the original concepts that were not very clear.
The object to be synchronized used last time is a hashtable, and the locking method is simple enough. However, it is too troublesome to lock every processing. Is there any thread-safe object? I found the answer in the SDK. Through hashtable. Synchronized() Method. We can package a synchronization version of hashtable for our use. Specifically, we can see how to implement the synchronization version through reflector, in this method, a new object is added and the following result is returned:
public static Hashtable Synchronized(Hashtable table)            {            if (table == null)            {            throw new ArgumentNullException("table");            }            return new Hashtable.SyncHashtable(table);            }            

The new object is a synchashtable object derived from hashtalbe. In this class ,. net has locked all the attributes and methods, so that we do not have to lock this object. Of course, this class is an internal private class. We cannot create it in the new method, but we can only obtain it through the synchronized method.
In this way, another problem occurs. is every time we declare a hashtable, we use the Synchronized Method to wrap it? Of course not. First, synchronization is meaningless for a single thread. Secondly, even for multi-threaded programs, if we can ensure that the reading and writing of hashtalbe will not conflict, then we do not need to synchronize it. After all, locking and unlocking also have performance loss. If you only need to use the manual lock for synchronization in a simple use, it will be OK, but if this hashtable is used in multiple places, so it is necessary to perform a synchronous packaging at the time of declaration. After all, human memory is limited. Maybe there is something wrong due to the absence of synchronous processing.
Another question was answered by a friend. Is the selection of locked objects. The object I lock is the hashtable object, but this code is displayed in the SDK:
Hashtable mycollection = new hashtable ();
Lock (mycollection. syncroot ){
Foreach (Object item in mycollection)
{
// Insert your code here.
}
Who is syncroot? The definition in the SDK is: Get the object that can be used to synchronize access to hashtable. The above is a full response to synchronous packaging, which comes with another object for Synchronous access. A little dizzy. No, it is quite dizzy. At this time, reflector again showed that it had no alternative power.
First, find the hashtable, and then the syncroot attribute. It doesn't matter if you don't check it. It's even dumb:

public virtual object SyncRoot            {            get            {            return this;            }            }

Return yourself? What is the concept? The most terrible thing is that the SDK has such a paragraph:
"The synchronization code must be inHashtableOfSyncrootInsteadHashtable. This ensures the correct operation of the Set derived from other objects. In particular, it maintains the correct synchronization with other threads, and these threads may be modifyingHashtableObject. "
I cannot lock myself, but by locking an attribute of the returned object, the beginner should be able to feel helpless and angry at the time. But I immediately recovered from my madness and turned my spirit back to the question itself from the indignation of a company called slight softness. Although the name of the company is Microsoft, the East-West aspects of the company are still relatively strong (most of them, and the requirements should not be too harsh ), therefore, I quickly realized that the problem still exists in myself (I am unwilling to accept this cruel fact every time ). Is it just to form a unified form when locking with other collection classes that implement icollection? Of course, this is also the reason, but it is not the core factor, I turned to my old friend for help. (The face is really thick. We are not an order of magnitude. I don't know how I feel every time I ask him a question that doesn't seem to be a problem? Contempt? I can't help but find myself guilty.) through his explanation and reading some materials, I initially got to know some of the locking objects.
First, the lock object must be of the reference type, which is understandable.
Second, in fact, as long as the locked object is a reference type object (it does not need to be the object to be synchronized, or even can be used by a new object) it can meet the requirements of the most basic thread synchronization. It seems that I have made a silly mistake. I take it for granted that the object to be synchronized needs to be locked, facts once again prove that the richness of my imagination is sometimes not an advantage.
Finally, my friend explained how to use the syncroot attribute. When we need to perform some custom control over the object's synchronous access, for example, we do not lock the reader of the set, only locks the writer Code). You can use the attributes of the object to control the attribute implementation code. Locking the object directly cannot control synchronous access.

I understand a lot of things, but it may take some time to apply it in my actual work. After all, the tasks on my line involve a large number of threads, even if there are, you also need to be careful when synchronizing the thread. After all, meaningless locking will slow the system down. When it gets quite slow, I believe that the user experience is no different from the deadlock.

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.