C # Multithreading Learning (iii) producers and consumers

Source: Internet
Author: User
Tags mutex

As I said before, each thread has its own resources, but the code area is shared, that is, each thread can perform the same function. The problem with this may be that several threads execute a function at the same time, causing data chaos and unpredictable results, so we have to avoid this happening.

C # provides a keyword lock that defines a piece of code as a mutex segment (critical section), where the mutex only allows one thread to enter execution at a time while the other threads must wait. In C #, keyword LOCK is defined as follows:

Lock (expression) Statement_block

Expression represents the object you want to track, usually an object reference.

If you want to protect an instance of a class, generally, you can use this;

If you want to protect a static variable (such as a mutex code fragment within a static method), use the class name generally.

And Statement_block is the code for the mutex segment, which can only be executed by one thread at a time.

The following is a typical example of using the Lock keyword, which describes the use and use of the lock keyword in a comment.

Examples are as follows:

using System;
using System.Threading;
namespace Threadsimple
{
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 exception
throw new Exception ("Negative Balance");
}
//The following code guarantees that
//No other threads will execute this code to modify the value of balance
//Therefore, the value of balance cannot be less than 0
Lock (this) until the current thread modifies the balance value complete
{
Console.WriteLine ("Current Thread:" +thread.currentthread.name);
If there is no protection for the lock keyword, then
//Another thread has executed the Balance=balance-amount modified balance value
///And this modification is not visible to this thread after the condition of the if is evaluated. This may cause the condition of if if it has not been set up
//However, the 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
}
}
}
Internal void dotransactions ()
{
for (inti = 0; I < 100; i++)
Withdraw (R.next ( -50));

}
Internal class Test
{
Static internal thread[] threads = new THREAD[10];
public static void Main () br> {
Account acc = new Account (0);
for (int i = 0; i < i++)
{
Thread t = new Thread (new Threadsta RT (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 ();
}
}
}

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.