Open 3 threads, the IDs of these 3 threads are a, B, C, each thread will have its own ID on the screen, and the output must be displayed in the order of ABC: ABCABC

Source: Internet
Author: User

1#include <stdio.h>2#include <process.h>3#include <windows.h>4 5 //Number of Threads6 Const intThread_num =3;7 8 //Number of Cycles9 Const intLOOP =Ten;Ten  One //Mutex Events AHANDLE G_hthreadevent[thread_num];//Child thread synchronization events -HANDLE G_semaphore;//the main thread synchronizes with the child thread - //volatile int g_count = 0; the intG_count =0; -  -Unsignedint__stdcall Threadfunction (void*PPM) - { +     intnum = * (int*) PPM; -ReleaseSemaphore (G_semaphore,1, NULL);//Signal Volume + + +  A      for(inti =0; i < LOOP; i++) at     { - WaitForSingleObject (G_hthreadevent[num], INFINITE); -         //InterlockedIncrement ((Lplong) &g_count); -g_count++; -  -printf"page%d thread id:%3d, thread print:%c\n", G_count, GetCurrentThreadID (), num +'A'); in  -SetEvent (g_hthreadevent[(num +1) %Thread_num]); to     } +  -     return 0; the } *  $ Panax Notoginseng intMainvoid) - { the     inti =0; + HANDLE Hthreadhandle[thread_num]; AG_semaphore = CreateSemaphore (NULL,0,1, NULL);//currently 0 resources, maximum allowed 1 simultaneous visits the  +      for(i =0; i < Thread_num; i++) -     { $G_hthreadevent[i] =CreateEvent (null, FALSE, FALSE, NULL); $     } -  -      for(i =0; i < Thread_num; i++) the     { -Hthreadhandle[i] = (HANDLE) _beginthreadex (nullptr,0, Threadfunction, &i,0, nullptr);Wuyi WaitForSingleObject (G_semaphore, INFINITE); the     } -  WuSetEvent (g_hthreadevent[0]); -  AboutWaitForMultipleObjects (Thread_num, Hthreadhandle,true, INFINITE); $  -      for(i =0; i < Thread_num; i++) -     { - CloseHandle (Hthreadhandle[i]); A CloseHandle (G_hthreadevent[i]); +     } the  - CloseHandle (g_semaphore); $  the     return 0; the}

Open 3 threads, the IDs of these 3 threads are a, B, C, each thread will have its own ID on the screen, and the output must be displayed in the order of ABC: ABCABC

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.