A probe into the multithreading mechanism of C # (4)

Source: Internet
Author: User
Expression represents the object that you want to track, usually an object reference. Generally, if you want to protect an instance of a class, you can use this; if you want to protect a static variable (such as a mutex snippet inside a static method), you can generally use the class name. And Statement_block is the code of the mutex, which can only be executed by one thread at a time.

Here's a typical example of using the Lock keyword, and I'll show you the usage and use of the lock keyword in the comments:

Lock.cs
Using System;
Using System.Threading;

Internal class Account
{
int balance;
Random r = new Random ();
Internal account (int initial)
{
balance = initial;
}

Internal int Withdraw (int amount)
{
if (Balance < 0)
{
//if balance is less than 0 throws an exception
throw new Exception (" Negative Balance ");
}
//The following code guarantees that
//No other thread will execute this code to modify the value of balance
//so that the value of balance is not possible to be less than 0 of
Lock (this) before the current thread modifies the value of balance.
{
Console.WriteLine ("Current Thread:" +thread.currentthread.name);
//If there is no protection for the lock keyword, then it is possible that after the condition of the IF has been evaluated
//Another thread has executed Balance=balance-amount modified the value of balance
//And this modification is not visible to this thread, So it could cause the if condition to be out of the
//However, the thread continues to execute balance=balance-amount, causing balance to be less than 0
if (balance >= amount)
{
Thread.Sleep (5);
Balance = Balance-amount;
Return amount;
}
Else
{
return 0;//transaction Rejected
}
}
}
Internal void dotransactions ()
{
for (int i = 0; i < i++)
Withdraw (R.next (-50, 100));
}
}

Internal class Test
{
Static internal thread[] threads = new THREAD[10];
public static void Main ()
{
Account ACC = new Account (0);
for (int i = 0; i <; i++)
{
Thread t = new Thread (The new ThreadStart (ACC). Dotransactions));
Threads[i] = t;
}
for (int i = 0; i <; i++)
Threads[i]. Name=i.tostring ();
for (int i = 0; i <; i++)
Threads[i]. Start ();
Console.ReadLine ();
}
}

While multithreading is common to an object, there are similar problems with common code, and the lock keyword should not be used. Here we need to use a class monitor in System.Threading, which we can call a monitor, which provides a scenario for threads to share resources.

The Monitor class can lock an object, and a thread can manipulate the object only if it gets the lock. The object lock mechanism ensures that only one thread can access the object at a time when it can cause confusion. Monitor must be associated with a specific object, but since it is a static class, it cannot be used to define an object, and all its methods are static and cannot be referenced using objects. The following code illustrates the case of locking an object using monitor:

......
Queue oqueue=new queue ();
......
Monitor.Enter (Oqueue);
...//Now the Oqueue object can only be manipulated by the current thread
Monitor.Exit (oqueue);//Release lock

As shown above, when a thread calls the Monitor.Enter () method to lock an object, the object is owned by it, and the other thread wants to access the object, only to wait for it to release the lock using the Monitor.Exit () method. To ensure that the thread eventually releases the lock, you can write the Monitor.Exit () method in the finally code block in the try-catch-finally structure. For any object that is locked by the monitor, there is some information about it in memory, one is a reference to the thread that holds the lock now, and the other is a reserve column, and the queue holds the thread that is ready to acquire the lock, and the third is a wait queue. The queue holds a reference to the queue that is currently waiting for the state of this object to change. When the thread that owns the lock is ready to release the lock, it uses the Monitor.pulse () method to notify the first thread in the wait queue, and the thread is transferred to the preliminary queue, and the thread in the prestaged queue can get the object lock immediately when the object lock is freed.

Here is an example of how to use the LOCK keyword and the monitor class to implement thread synchronization and communication, as well as a typical producer and consumer problem. In this routine, the producer and consumer threads are alternately, the producer writes a number, the consumer reads and displays immediately, and I will describe the program's essentials in the comments. The system namespaces used are as follows:

Using System;
Using System.Threading

The above is the multithreading mechanism of C # (4) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.