Windows multithreaded Programming

Source: Internet
Author: User
Tags mutex semaphore

Processes together to implement a task or share computer resources, There are two types of relationships:

1. A synchronization relationship , which refers to the process of accomplishing a task, because it needs to wait for the order of execution to be reconciled in some locations, passing the constraints of the Message.

2. Mutual exclusion relationships between processes that are constrained by competing with exclusive resources, such as one process using a printer, and another process having to wait for it to be used.

Critical Resources : A resource that allows only one process at a time (which must be mutually exclusive), such as exclusive hardware resources .....

critical segment: refers to the process must be mutually exclusive execution of the program segment, which implements the operation of critical Resources.

The key area object Is: critical_section When a thread enters a critical area, other threads block the wait until the thread releases ownership of the critical zone.

#include <windows.h>#include<stdio.h>Static intNumber=Ten; critical_section criticalsection; DWORD WINAPI threadone (lpvoid lpparameter) {printf ("window 1 ticketing start: \ n");  while(1) {entercriticalsection (&criticalsection); if(number>0) {printf ("window 1 sold%d tickets ... \ n", number); number--; Sleep ( +); } leavecriticalsection (&criticalsection); Sleep ( -); }    return 0;} DWORD WINAPI threadtwo (lpvoid lpparameter) {printf ("window 2 ticketing start: \ n");  while(1) {entercriticalsection (&criticalsection); if(number>0) {printf ("window 2 sold%d tickets ... \ n", number); Sleep ( +); number--; } leavecriticalsection (&criticalsection); Sleep ( -); }     return 0; } intmain () {HANDLE hone,htwo; InitializeCriticalSection (&criticalsection); printf ("***********************vpoet******************\n"); HOne=createthread (NULL,0, threadone,null,0, NULL); Htwo=createthread (NULL,0, threadtwo,null,0, NULL);     CloseHandle (HOne);     CloseHandle (htwo);  while(TRUE) {if(number==0) {printf ("sorry, The tickets are sold out!\n"); DeleteCriticalSection (&criticalsection); return 0; }         Else         {             Continue; }         }          return 0; }

semaphore mechanism : the signal volume and P operation, v operation of two parts, can solve the mutual exclusion and synchronization Problems. The semaphore (s) is an integer variable that can only be accessed by two standard primitives, which are recorded as P operation and V Operation Respectively.

Defined as Follows:

P (s) {     while0         // null operation          1;  } V (s) {    1;}

The semaphore can solve the critical section problem of n process , n process share a common variable mutex, its initial value is 1, the result of any one process pi is as follows:

 do {    P (mutex);    Critical secition    V (mutex);    Non critical secition}while (1);

Semaphores can also resolve inter-process synchronization Issues.

Solving thread synchronization problems with semaphores

#include <windows.h>#include<stdio.h>Static intNumber=Ten;  HANDLE Sem; DWORD WINAPI threadone (lpvoid lpparameter) {printf ("window 1 ticketing start: \ n");  while(1)     {          //signal Volume > 0, minus 1WaitForSingleObject (sem,infinite); if(number>0) {printf ("window 1 sold%d tickets ... \ n", number); number--; Sleep ( +); }         //signal Volume < 0, plus 1ReleaseSemaphore (Sem,1, NULL); Sleep ( -); }     return 0; } DWORD WINAPI threadtwo (lpvoid lpparameter) {printf ("window 2 ticketing start: \ n");  while(1) {waitforsingleobject (sem,infinite); if(number>0) {printf ("window 2 sold%d tickets ... \ n", number); Sleep ( +); number--; } ReleaseSemaphore (Sem,1, NULL); Sleep ( -); }     return 0; } intmain () {HANDLE hone,htwo; printf ("***********************vpoet******************\n"); HOne=createthread (NULL,0, threadone,null,0, NULL); Htwo=createthread (NULL,0, threadtwo,null,0, NULL); //Create semaphore, initial 1, maximum count of 1Sem=createsemaphore (NULL,1,1, NULL);     CloseHandle (HOne);     CloseHandle (htwo);  while(TRUE) {if(number==0) {printf ("sorry, The tickets are sold out!\n");             CloseHandle (Sem); return 0; }         Else         {             Continue; }         }          return 0; } 
View Code

the specific realization of signal volume : With the process scheduling, eliminate the busy waiting Phenomenon.

Basic Idea:

In the place where the p-operation loop is waiting, The Abort processor is involved, into the waiting for the Action.

During v operation, the extraction process from the wait queue becomes READY.

Signal Volume definition

struct {       int: value;  A numeric variable        struct process *L; a PCB queue       } Semaphoresemaphore S;

P operation

   P (S):      s.value=s.value-1;               if s.value<0  then save the scene, attach              the process to the S.L queue, wait for the rescheduling

Request to allocate a resource represented by s, if S.value < 0, represents the system without this resource, the requester is Blocked.

V Operation

   V (S):          s.value:=value+1                  if s.value≤0 then                  takes a process from the S.L queue and hangs into the ready Queue. 

The process releases a resource represented by s, if S.value <= 0, indicating that there is still a process waiting for s and is blocked, all to wake up One.

Enhancement

Shared resources are represented by shared data structures, where the critical segments of the shared resources are concentrated in the pipe, and the critical program in the tube allows only one process call at a Time.

Main composition: shared Data structure, a set of functions for shared data structure operation, initialization program of data Structure.

Windows multithreaded Programming

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.