Multithreading under Windows (Producer consumer issues: 3 producers, one consumer, 4 buffers)

Source: Internet
Author: User

The original author provides the source code for two kinds of situations:

First: 1 producers 1 Consumers 1 buffers

Second: 1 producers 2 Consumers 4 buffers

======================== Below is a case of 4 buffers for 1 consumers of 3 producers who have been modified by the author's source code ==================

1 Producer 2 Consumer 4 buffer #include <stdio.h> #include <process.h> #include <windows.h>//Set console output color BOOL  
    Setconsolecolor (WORD wattributes) {HANDLE hconsole = GetStdHandle (Std_output_handle);  
      
    if (Hconsole = = INVALID_HANDLE_VALUE) return FALSE;  
Return Setconsoletextattribute (Hconsole, wattributes);  const int end_produce_number = 9;          Number of production Products const int buffer_size = 4;          Number of buffers int g_buffer[buffer_size];  
Buffer pool int g_i, G_j;  
Signal quantity and key segment critical_section G_cs;  

HANDLE G_hsemaphorebufferempty, G_hsemaphorebufferfull;
int data=0; Producer thread function unsigned int __stdcall producerthreadfun (pvoid PM) {//for (int i = 1; I <= end_produce_number; i++ //{while (data<end_produce_number) {//waiting for an empty buffer to appear waitforsingleobject (g_hsemaphorebuffere  
  
        Mpty, INFINITE); 
		Mutually exclusive access buffer entercriticalsection (&AMP;G_CS); if (data==end_produce_number) {leavecriticalsection (&AMP;G_CS);
		Break
        } data=data+1;  
        G_buffer[g_i] = data;
		printf ("Producer puts data in buffer pool in%d buffer%d\n", g_i, G_buffer[g_i]); 
        printf ("Number%d producers drop data in buffer pool%d buffers%d\n", GetCurrentThreadID (), G_i, G_buffer[g_i]);  
        G_i = (g_i + 1)% Buffer_size; 
		LeaveCriticalSection (&g_cs);
        Sleep (50);  
	Inform the consumer that there are new data ReleaseSemaphore (G_hsemaphorebufferfull, 1, NULL);  
    }/*/printf ("The producer completes the task, the thread finishes running \ n");  
return 0;  
        }//consumer thread function unsigned int __stdcall consumerthreadfun (pvoid PM) {while (true) {//Waiting for Non-empty buffer to appear  
          
        WaitForSingleObject (G_hsemaphorebufferfull, INFINITE);  
        Mutually exclusive access buffer entercriticalsection (&AMP;G_CS);  
        Setconsolecolor (Foreground_green); /*printf ("Number%d consumers remove data from%d buffers in buffer pool%d\n", GetCurrentThreadID (), G_j, G_buffer[g_j]);
        /printf ("Number%d consumers remove data from buffer pool%d buffers%d\n", GetCurrentThreadID (), G_j, G_buffer[g_j]); Setconsolecolor (Foreground_red | Foreground_green |  
        Foreground_blue);  
            if (g_buffer[g_j] = = end_produce_number)//End Sign {leavecriticalsection (&AMP;G_CS);  
            Inform other consumers of new data (end sign)//releasesemaphore (g_hsemaphorebufferfull, 1, NULL);  
        Break  
        } G_j = (g_j + 1)% Buffer_size;  
  
        LeaveCriticalSection (&g_cs); Sleep (50);  
    Some work to do ReleaseSemaphore (G_hsemaphorebufferempty, 1, NULL);  
    } setconsolecolor (Foreground_green);  
    printf ("Customer with number%d received notification, thread ends running \ n", GetCurrentThreadID ()); Setconsolecolor (foreground_red | Foreground_green |  
    Foreground_blue);  
return 0;  
    int main () {printf ("Producer Consumer problem 3 producer 1 Consumer 4 buffer \");  
  
    printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");  
    InitializeCriticalSection (&g_cs);  
    Initializes the semaphore, one record has the number of buffers for the product, and the other records the number of empty buffers. G_hsemaphorebufferempty = CreateSemaphore (NULL, 4, 4, NULL);  
    G_hsemaphorebufferfull = CreateSemaphore (null, 0, 4, NULL);  
    g_i = 0;  
    G_j = 0;  
  
    memset (g_buffer, 0, sizeof (g_buffer));  
    const int threadnum = 4;  
    HANDLE Hthread[threadnum];  
	Producer Threads 3 Hthread[0] = (HANDLE) _beginthreadex (null, 0, producerthreadfun, NULL, 0, NULL);  
    HTHREAD[1] = (HANDLE) _beginthreadex (null, 0, producerthreadfun, NULL, 0, NULL); 
    HTHREAD[2] = (HANDLE) _beginthreadex (null, 0, producerthreadfun, NULL, 0, NULL); 

    Consumer thread 1 Hthread[3] = (HANDLE) _beginthreadex (null, 0, consumerthreadfun, NULL, 0, NULL);  
    WaitForMultipleObjects (Threadnum, Hthread, TRUE, INFINITE);  
  
    for (int i = 0; i < threadnum i++) CloseHandle (hthread[i));  
    Destruction of signal volume and critical segment CloseHandle (G_hsemaphorebufferempty);  
    CloseHandle (G_hsemaphorebufferfull);  
    DeleteCriticalSection (&g_cs);  
return 0;  }

The results of the operation are as follows:



reference:http://blog.csdn.net/morewindows/article/details/7577591




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.