C # simple multithreading (synchronization and priority)

Source: Internet
Author: User

Question:

McDonald's has two chefs (workers:) and three sales staff (workers:, 23 ). The cook produces a hamburger and puts it on the shelf. The shelf is limited in size, and a maximum of six Hamburgers can be placed. 11 and 12 cannot be placed on the shelf at the same time. 11 has priority. Sales personnel are responsible for selling food. When three sales personnel take food, the shelf cannot be empty, and the three personnel cannot take the food at the same time. The highest priority is 23, and the lowest priority is 21. 21 is the fastest to sell, with the highest acquisition frequency, followed by 22.
One day's workload is to sell 70 hamburgers.

 

Concepts  

Blocking: The thread is suspended before the function returns the result.

Non-blocking: return immediately after the function is executed, without blocking the thread

Synchronization: The thread is suspended because the function is not returned after execution;

Asynchronous: The function returns immediately, and the result notifies the caller through an event or signal;

 

Synchronous Message Processing is like a simple read/write operation in Linux. They need to wait for the operation to succeed before returning. asynchronous processing is similar to the select/poll multiplexing Io operation, when a message of interest is triggered, it is triggered by a message trigger mechanism notification to process the message.

Process: when a program runs, it is a process, including the memory and system resources used by the running program. A process can contain multiple threads.

 

Thread: A thread is an execution stream in a program. Each thread has its own proprietary register (Stack pointer, program counter, etc.), but the code zone is shared, that is, different threads can execute the same function.

 

Multithreading: A program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks. CPU is allocated to the time slice!

 

Main thread Methods: strart (), sleep (INT), abort (), suspend (), resume ()

 

Thread priority: In the C # application, you can set five different priorities, from high to low, which are highest, abovenormal, normal, belownormal, lowest, if the priority is not specified during thread creation, the system defaults to threadpriority. normal.

 

Thread Synchronization(The framework already provides three locking mechanisms for us: the monitor class, the lock keyword, And the mutex class.
):

A. C # provides a keyword lock, which defines a piece of code as a critical section. A mutex section allows only one thread to enter the execution at a time point, other threads must wait.

In C #, the keyword lock is defined as follows:

Lock (expression) statement_block

B. Main usage of Monitor

Monitor. Enter (OBJ );

(Expression)

Monitor. Exit (OBJ );

C. mutex usage

Mutex = new mutex ();

Mutex. waitone ();

(Expression)

Mutex. releasemutex ();

For example, lock mutex (including multi-thread usage, multi-thread priority, and synchronous usage ):

 

Using system; using system. collections. generic; using system. text; using system. threading; namespace testthread {class program {private static object lockobject = new object (); Private Static object lockobject2 = new object (); Private Static int igethbnum = 0; private Static int iputhbnum = 0; Private Static int count21 = 0; Private Static int count22 = 0; Private Static int count23 = 0; private stati C int count11 = 0; Private Static int count12 = 0; static void main (string [] ARGs) {console. writeline ("main thread running, thread ID:" + thread. currentthread. managedthreadid. tostring (); thread chushi1 = new thread (puthb); chushi1.priority = threadpriority. abovenormal; chushi1.name = "11"; chushi1.start (); thread chushi2 = new thread (puthb); chushi2.priority = threadpriority. normal; chushi2.name = "12"; chushi2.sta RT (); thread consume21 = new thread (gethb); consume21.priority = threadpriority. normal; consume21.name = "21"; consume21.start (); thread consume22 = new thread (gethb); consume22.priority = threadpriority. normal; consume22.name = "22"; consume22.start (); thread consume23 = new thread (gethb); consume23.priority = threadpriority. normal; consume23.name = "23"; consume23.start (); console. readkey ();} p Ublic static void puthb () {string Strid = thread. currentthread. name. tostring (); console. writeline ("{0} cook starts making hamburger,", Strid); While (true) {If (iputhbnum> = 6) {console. writeline ("cook {0}, a maximum of six Hamburgers can be placed. Please ask the salesman to take it and try again! ", Strid); thread. sleep (1000);} else {If (igethbnum> = 70 | count11 + count12> = 70) {If (Strid = "11") {console. writeline ("cook {0}, put a total of {1} hamburgers on the shelf! ", Strid, count11);} else if (Strid =" 12 ") {console. writeline (" chef {0}, put a total of {1} Hamburg on the shelf! ", Strid, count12);} break;} Lock (lockobject) {iputhbnum ++;} If (Strid =" 11 ") {count11 ++; console. writeline ("cook {0}, put {1} hamburger on the shelf! There are {2} hamburgers on the shelf now! ", Strid, count11, iputhbnum);} else if (Strid =" 12 ") {count12 ++; console. writeline ("cook {0}, put {1} hamburger on the shelf! There are {2} hamburgers on the shelf now! ", Strid, count12, iputhbnum) ;}}} public static void gethb () {string Strid = thread. currentthread. name. tostring (); console. writeline ("{0} salesman takes Hamburg,", Strid); While (true) {If (iputhbnum <= 0) {thread. sleep (1, 1000); console. writeline ("{0} There are already 0 hamburgers on the shelf. Please wait for the cook to make it! ", Strid);} else {lock (lockobject2) {igethbnum ++; iputhbnum --;} If (Strid =" 23 ") {count23 ++; console. writeline ("salesman 23 has sold --- {0 }! ", Count23); thread. sleep (3000);} else if (Strid = "22") {count22 ++; console. writeline ("salesman 22 sold --- {0 }! ", Count22); thread. sleep (2000);} else if (Strid = "21") {count21 ++; console. writeline ("salesman 21 has sold --- {0 }! ", Count21); thread. Sleep (1000) ;}} if (igethbnum >=70) {console. writeline (" sold out! "); If (Strid =" 23 ") {console. writeline ("salesman Sales No. 23: {0}", count23);} else if (Strid = "22") {console. writeline ("salesman Sales No. 22: {0}", count22);} else if (Strid = "21") {console. writeline ("sales volume of salesman No. 21: {0}", count21) ;}break ;}}}}}

Result:

The lock can be replaced by monitor and mutex.

 
Monitor. Enter (lockobject );

Iputhbnum ++;

Monitor. Exit (lockobject );

Or

Mutex1.waitone ();


IPutHBnum ++;

Mutex1.ReleaseMutex ();

 

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.