Consumer/Producer Multithreaded Program


I have used VS.NET to implement this program.

Double click on Produce_Consumer.Zip and extract all the files and folders in to a folder in C drive.  

Run the project using VS.NET:

Double click on MultiThread.sln (Prject file). Then run the project (press F5). The Form1 will appear as shown below. 

Run using command-line prompt.

Copy all the .cs files (From1.cs, Consumer.cs, Form1.cs and Producer.cs) in to a folder in C drive and comple it using 

C:\FolderName> csc *.cs

This will create a Form1.exe file inside the folder. Then double click it run it. 

This is simple multi-threading program that adds and removes elements in an ArrayList. Producer button will creates a producer thread that adds elements in to the ArrayList. The maximum number of elements can be added to this ArrayList are 100 elements and the producer thread has to wait until the consumer thread/threads (creates by pressing consumer button) removes elements from the ArrayList. Then Producer thread starts to add more elements to the ArrayList. 

public const int producerLimit = 200;

The maximum number of elements can be produce by Producer thread can be change using the constant variable producerLimit. 

Synchronized

public static ArrayList ItemContainer = ArrayList.Synchronized(new ArrayList());

Using Synchronized method we can make a Synchronized ArrayList (Thread-Safe). 

Interlocked provides atomic operations for variables that are shared by multiple threads. It contains methods such as Increment, Decrement, CompareExchange and Exchange. Interlocked.Increment(ref totalProduce); 

Volatile

In multithreading environment the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread. 

Pressing Consumer button multiple times can create multiple consumer threads.

Press Exit button to close the window. 


Similar Articles