Thread synchronization, thread security example

Source: Internet
Author: User
Namespace  Consoleapplication22
{
Class Program
{

Static Void Main ( String [] ARGs)
{


Thread [] TS = New Thread [ 30 ];
Testdemo TD = New Testdemo ();
Int I;
For (I = 0 ; I < 30 ; I ++ )
{
TS [I] = New Thread (TD. test1 );

TS [I]. Start ();
}



While ( True )
{
Bool Flag = TD. Test2 ();

If (FLAG)
Break ;
}

Console. readkey ();
}



}


Public Class Testdemo
{
Private Hashtable sh = New Hashtable ();
Private Static Object Synlock = New Object ();
Int I = 0 ;

Public Void Test1 ()
{

Lock (Synlock)
{

++ I;
Thread. Sleep ( 1000 );
System. Diagnostics. Debug. writeline (I + " Roy " );
Sh. Add (I, I );
}


}

Public Bool Test2 ()
{
If (I ! = 30 && ! Sh. containskey ( 30 ))
Return False ;

Lock (Synlock)
{
Foreach (Dictionaryentry de In SH)
{
Console. writeline ( " ............... " + De. Key. tostring () + " ................ " + De. value. tostring ());
}

Return True ;
}
}
}
}
Lock to protect static members. Generally, typeof (class name) is used) View code

View code

   Internal     Class Account
{
Int Balance;
Random R = New Random ();
// Private Static object synlock = new object ();

Internal Account ( Int Initial)
{
Balance = Initial;
}

Internal Int Withdraw ( Int Amount)
{

If (Balance < 0 )
{
// If the balance is less than 0, an exception is thrown.
Throw New Exception ( " Negative balance " );
}
// The followingCodeBefore the balance value is modified by the current thread
// No other threads will execute this code to modify the balance value.
// Therefore, the balance value cannot be smaller than 0.
System. Diagnostics. Debug. writeline ( " Current thread: " + Thread. currentthread. Name );
// Console. writeline ("current thread:" + thread. currentthread. Name );
// If the lock keyword is not protected, it is possible that
// The other thread executes balance = balance-amount and modifies the balance value.
// This modification is invisible to this thread, so it may cause the if condition to be invalid.
// However, this thread continues to execute balance = balance-amount, so the balance may be less than 0
If (Balance > = Amount)
{
// Thread. Sleep (5 );
Balance = Balance - Amount;
Return Amount;
}
Else
{
Return 0 ; // Transaction rejected
}

}
Tracesource TS = New Tracesource ( " Getomlogsource " );
Internal Void Dotransactions ()
{

Lock ( This )
{
// System. Diagnostics. Debug. writeline ("current thread:" + thread. currentthread. Name );

For ( Int I = 0 ; I < 100 ; I ++ )
Withdraw (R. Next ( - 50 , 100 ));
}
}
}



Class Program
{
Static Internal Thread [] threads = New Thread [ 10 ];
Public Static Void Main ()
{
Account ACC = New Account ( 0 );
For ( Int I = 0 ; I < 10 ; I ++ )
{
Thread t = New Thread ( New Threadstart (Acc. dotransactions ));
Threads [I] = T;
}
For ( Int I = 0 ; I < 10 ; I ++ )
Threads [I]. Name = I. tostring ();
For ( Int I = 0 ; I < 10 ; I ++ )
Threads [I]. Start ();
Console. Readline ();
}

}

Lock to protect instance members. Generally, this

Thread security: as its name implies, it uses the thread synchronization technology to allow multiple threads to securely access the same resource.(For example, a static global variable or a static global set)

The following are my correct conclusions after one-step debugging, trace log tracking, vs stress testing tool for concurrent testing! There has always been a game about ensuring thread security and concurrency performance at the same time. After some research, several processing methods are obtained: thread security allows multiple threads to securely access the same shared resource. Generally, various locks are used to ensure thread synchronization so that shared resources do not encounter unexpected logical errors or exceptions. After the lock is applied, the threads in your system that want to read shared resources can only wait, because the lock makes your system completely free of concurrency, this is surprisingly poor user experience in the formal system of a single server on multiple clients. Here I will talk about the solution in two project scenarios: (1) for systems with low real-time performance, we can clone a copy of shared resource objects, after all related business operations are performed on the replica, the shared resource is truly locked, and the address of the copy object is assigned to the shared resource. In this way, the shared resource is locked as little as possible, improved Program Concurrency also ensures thread security. For example, the shared resource is a dataset of the server program. N client programs can write this dataset through remote calls, and they also need to read this DataSet. When a client requests to modify this dataset, I usually generate a copy of this dataset for operation. After the operation is complete, lock the shared resource dataset and assign the reference address to it, so that other clients that require reading this shared resource will not be blocked. (2) For systems with high real-time requirements, such as IM systems, I will adopt read/write locks to deal with this problem. read/write locks can ensure that multiple read locks are obtained, however, only one update lock or write lock can be obtained (exclusive ). For example, upgrading a read lock to a write lock in another atomic operation is very useful. For example, if you want to write some nonexistent items in another list, you may perform the following steps: 1. Obtain a read lock. 2. test. If you want to write something in the list, release the lock and return it. 3. Release the read lock. 4. Obtain a write lock. 5. add items, write items, and 6. Release the write lock. The problem is that another thread may have modified the list between step 3 and step 4. An updatable lock is similar to a read lock except that it can be converted into a write lock in an atomic operation. You can use it like this: 1 call enterupgradeablereadlock to obtain the updatable lock. 2. Execute some read operations. For example, you can determine that the content to be written is not in the list. 3. Call enterwritelock. This method upgrades the updatable lock to the write lock. 4. Execute the write operation. 5. Call the exitwritelock method. This method converts the write lock back to the updatable lock. 6. Continue to perform some read operations or do nothing. 6. Call exitupgradeablereadlock to release the updatable lock. 7. From the caller's perspective, it looks like a nested/recursive lock. functionally, in step 3, readerwriterlockslim releases the read lock in an atomic operation and obtains the write lock.

According to the error message, we can see that when running an application in the debugger is not the control creator thread trying to call the control, the debugger will trigger
Invalidoperationexception, and the message is displayed: "never create control name
The thread to access it ." To put it bluntly, resource access is inconsistent. The caller thread of the control is not the Creator thread of the control. This is the inevitable result of. Net's implementation of the secure resource access mechanism. Access
Windows Forms controls are not thread-safe in nature. If multiple threads operate on the status of a control at the same time, the control may be forced to enter an inconsistent state.

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.