VC + + thread synchronization (v) semaphore use example

Source: Internet
Author: User
Tags semaphore textout

Signal Volume (Semaphore)


the Semaphore is the kernel object, which uses several image examples to Describe.


1 assume that there are 5 positions, and there are a lot of people outside to come in, then when the 5 positions are occupied by people

, other people have to wait in line, everyone uses different time, 5 occupied position, two of which are completed, then, the top two people in the queue can be used, but up to 5 people can use at the same time, this is the Semaphore.


2 for example, we create a thread pool in the server, which consists of 5 threads, which means that up to 5 requests are processed at the same time, once more than 5, the request is put into the buffer, and when one or more requests (up to 5) are completed, the other requests are processed from the Buffer.



Characteristics of the Semaphore:

1 semaphore count with the same amount of resources

2 contains a usage counter, a maximum resource counter, and a current resource counter

3 Maximum resource counter to control the largest child element

4 Current Resource counter indicates the number of resources currently available

The trigger rule and the current resource counter are Relevant.



Trigger Rule:

1 if the current resource >0 the semaphore is in the triggered state

2 if the current resource = 0, The semaphore is not in the triggered state

3 system will never let current resource technology become negative

4 The current resource count will never be greater than the maximum resource count



Run the Process:

1 Suppose we create a semaphore whose maximum resource count is 5 and the current resource count

also for 5 (typically The maximum resource count value is the same as the current resource meter value in the middle of the initialization process) because the current resource counter is greater than 0, the semaphore is in a triggered State.


2 in order to gain access to the protected resource, the thread calls the wait function and goes to the handle of the semaphore, inside, the wait function detects the current resource counter technology, if it is greater than

0 ( greater than 0 trigger state ) Then the wait function will subtract the current resource counter by 1 and let the calling thread

continues to run, if it equals 0 (not triggered ) then the system causes the thread to go into a wait state (not digesting the cpu), and when another thread increments the current resource count of the semaphore, the system

remember which threads are waiting so that they can program the scheduled state (and decrement the current resource count Accordingly)


The 3 thread increments the current resource counter of the semaphore through Releasesemaphore.


Look at the Code:

Global variable HANDLE g_hsem;


Create a semaphore CreateSemaphore (null,2,2,null);

Parameter 1 windows: Permissions

Parameter 2 represents the current resource count value

Parameter 3 maximum resource counter, which indicates that the semaphore can manage 2 threads at the same time

Parameter 4 object Name ...


Should be created, the current resource count is greater than 0, so he is the trigger State.

Create 5 threads and compete in two locations with 5 threads, reflecting the intense Competition.


The height Int cychar = hiword (getdialogbaseunits ()) based on the dialog box font in the case wm_create:{//system; ThrParams4.hwnd  = hwnd;thrparams4.cychar = cychar;//create Semaphore  g_hsem = createsemaphore (NULL,  2, 2,null); Handle handleemployee1 = createthread (NULL, 0, THREMPLOYEEPROC1, &THRPARAMS4 ,  0, null); Handle handleemployee2 = createthread (NULL, 0, THREMPLOYEEPROC2, &THRPARAMS4 ,  0, null); Handle handleemployee3 = createthread (NULL, 0, THREMPLOYEEPROC3, &THRPARAMS4 ,  0, null); Handle handleemployee4 = createthread (NULL, 0, THREMPLOYEEPROC4, &THRPARAMS4 ,  0, null); Handle handleemployee5 = createthread (NULL, 0, THREMPLOYEEPROC5, &THRPARAMS4 ,  0, null);//close thread handle CloseHandle (handleEmployee1); CloseHandle (handleEmployee2); CloseHandle (handleEmployee3); CloseHandle (handleEmployee4); CloseHandle (handleEmployee5);} Case wm_destroy://off Semaphore CloseHandle (g_hsem); PostQuitMessage (0); break;


Let's take a look at the thread Function.


Dword winapi thremployeeproc1 (lpvoid lp) {pparams param4 = static_cast<pparams > (lp);//wait for this semaphore    forever block   If the Semaphore's    current resource count   greater than 0  triggers   estoppel WaitForSingleObject ( g_hsem,infinite);   //when He returns   The current resource count will   1//sleep for 2 seconds sleep (2000);//gets The current number of milliseconds dword dwcurtime  = gettickcount ();//get dchdc hdc = getdc (param4->hwnd);//display text bool bf =  textout (hdc, 0,  (g_iline4++) *param4->cychar, _t ("employee thread 1 is using the company online"),  lstrlen (_T (" Employee Thread 1 is using the company Internet "));//release Dc releasedc (param4->hwnd,hdc);//cycle 10 seconds to exit while  (true) {if  ((GetTickCount ()  - dwcurtime)  > 1000 * 10) {hdc hdc = getdc (param4->hwnd); SetTextColor (hdc, rgb (255, 0, 0)); TextOut (hdc, 0,  (g_iline4++) *param4->cychar, _t ("employee thread 1 has not been using the company online"),  lstrlen (_t (" Employee Thread 1 has not used the company online ")); ReleaseDC (param4->hwnd, hdc); break;} Sleep (1000);} Releasing the semaphore   semaphore handle   Enter   and// 1 represents add 1  current resource counter +1   can +2 +3  but now add 1 most suitable//  The last parameter is to reverse the number of last resource counters    Most of the time   do not need this thing ReleaseSemaphore (g_hsem,1,null); return 0;}


Effect:

We find that the number of the Internet is controlled by the semaphore, up to

There are two employees who can access the Internet.

650) this.width=650; "src=" https://s4.51cto.com/wyfs02/M02/9C/F1/wKioL1l4IUKTNyFVAAAlHXs53n8869.png-wh_500x0-wm_ 3-wmp_4-s_1420724754.png "title=" g%ooc_n) z814jc%pd5_xizf.png "alt=" wkiol1l4iuktnyfvaaalhxs53n8869.png-wh_50 "/ >


Have not understood the continuous I qq:2438746951

AC group: 140066160


Source Code address: http://down.51cto.com/data/2329794









This article is from the "12148490" blog, please be sure to keep this source http://12158490.blog.51cto.com/12148490/1951092

VC + + thread synchronization (v) semaphore use example

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.