. Net (C #): Use a thread-safe set to quickly solve producer and consumer problems

Source: Internet
Author: User

Program Demonstration:

First, enter the maximum capacity, for example, input 10:

 

Next, the production line is generated. At first, there are only 0 projects. Now we start to produce 5 projects and enter 5 in "production quantity", for example:

 

Click "production" and five projects will be produced:

 

Next we will create 12 projects and add the previous 5 projects. At this time, a total of 17 projects will be produced, but the total capacity is 10, so there will be 7 production projects waiting (thread blocking ):

 

Next, we will produce 10 projects. Seven production projects are waiting, and the requirements for subsequent production projects will overlap:

 

The current situation is: 10 projects have been produced, and 17 projects are waiting for production. Below we will consume 5 projects, and the results are as follows:

 

After five projects are consumed, the projects waiting for production begin production immediately, knowing that the capacity is up to 10 again, and the number of projects waiting for production on the left is changed to 12 (5 fewer ).

The following figure shows the result of directly consuming 100 items:

 

Since 10 projects were produced and 12 projects were waiting for production, after 22 projects were consumed, the subsequent consumption could not be met, so 78 projects were waiting.

 

Finally, we created 80 projects, 78 of which were consumed, and 2 were left on the production line, for example:

 

 

There are many solutions to consumer problems, but it is very easy to use the. NET 4.0 + thread security set. You do not need to customize the thread synchronization logic. You can directly use the thread security set and then operate it with multiple threads. Of course, you can use blockingcollection to make it more specific, it is not a set in a strict sense, but a package to another thread security set to enable blocking. Use blockingcollection to define the entire production line set. The problem of production and consumption is to add and delete the blockingcollection. Here we will inherit the unique advantages of blockingcollection. When you add a value to a full set, or deleting a value from an empty set will cause the operation thread to be blocked, knowing that this requirement is completed, otherwise the operation thread will be blocked all the time.

 

The core of the entire execution is Operator and requestitem.

Operator contains blockingcollection and provides encapsulation methods to call the ADD and take operations of blockingcollection for production and consumption.

Any operation is represented by requestitem. This type stores the number of operations, that is, 5 of the "five projects. For commands that can be completed, blockingcollection is obviously not blocked, and then the production or consumption operations are performed based on the number of operations. Finally, requestitem is deleted. However, if the command cannot be met, blockcollection will be blocked and the corresponding requestitem will be left. The number of operations indicates the number of waiting jobs, and requestitem can also be superimposed.

 

Refer:

 

The operator and requestitem inherit the inotifypropertychanged interface to notify the WPF attribute changes. At the same time, the production and consumption wait queue is saved to the observablecollection in the operator, it is a bit like viewmodel in mvvm, but the program is not written in strict mvvm mode.

 

 

Operator type:

The consumers attribute indicates the consumption waiting queue.

The producers attribute indicates the production waiting queue.

Count and capacity represent the number of projects and total capacity of the current production line respectively. Note that because the total capacity does not change, there is no need to change the notification like the Count attribute.

Public observablecollection <requestitem> consumers {Get; private set ;}

Public observablecollection <requestitem> Producers {Get; private set ;}

Public int capacity {Get; private set ;}

 

# Region count

 

Private int _ COUNT = 0;

Public int count

{

Get {return _ count ;}

Protected set

{

If (_ count! = Value)

{

_ COUNT = value;

Onpropertychanged ("count ");

}

}

}

 

Requestitem is simpler. Only one count attribute represents the operand.

 

Finally, the execution of the production or consumption operations goes smoothly. We use the production method: produce as an example (there is a comment in the Code ):

Public void produce (INT count)

{

// Use another thread to operate blockingcollection

Task. Factory. startnew () =>

{

// Generate requestitem

VaR item = new requestitem (count );

// Add requestitem to the production waiting queue

// The uiaction method uses WPF to indirectly call the invoke-related operations of the WPF dispatcher.

Uiaction () => producers. Add (item ));

// Try the production operation

For (INT I = 0; I <count; I ++)

{

// Call the add method of the internal blockingcollection

Blockingqueue. Add (0 );

// Important: if the code runs to this point, it indicates there is no blocking, and production is successful.

Uiaction () =>

{

// Reduce the number of waiting operations by 1

-- Item. count;

// Add the number of production line projects to 1

++ Count;

});

}

// All production requirements are completed, removing this production requirement from the queue

Uiaction () => producers. Remove (item ));

});

}

 

OK, the overall framework of the program is almost like this, there are some details and interface processing will not be discussed, if necessary, readers can refer to the source code.

 

Source code download

Note: This is an archive of Microsoft SkyDrive. Please download it directly in your browser. Some download tools may not be available for download.
Source code environment: Microsoft Visual C #2010 Express

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.