Category: Windows programming C + + 2012-10-27 15:38 3270 people read reviews (6) favorite reports The fourth question (Thunder written question): Write a program, open 3 threads, the IDs of the 3 threads are a, B, C, each thread will print its own ID on the screen 10 times, the output must be displayed in the order of ABC, such as: Abcabc .... recursion in turn.
[CPP]View Plaincopy
- #include <stdio.h>
- #include <process.h>
- #include <windows.h>
- #define G_HTHREADEVENT (n) g_hthreadevent# #1
- unsigned int __stdcall fun (void *ppm);
- Number of threads
- const INT thread_num = 8;
- Number of Cycles
- const INT LOOP = 6;
- Mutex events
- HANDLE G_hthreadevent[thread_num];
- int main ()
- {
- printf ("\ t sub-thread loops 10 times, then the main thread loops 100 times, then goes back to the child thread loop 10 times, \ n then goes back to the main thread and loops 100 times, so loop 50 times \ n");
- int i = 0, J;
- HANDLE Hdl[thread_num];
- For (i = 0; i < thread_num; i++)
- G_hthreadevent[i] = CreateEvent (null,false,false,null);
- //The thread number is passed in as a thread parameter, first converted to a pointer, then converted to shaping,
- For (i = 0; i < thread_num; i++)
- Hdl[i] = (HANDLE) _beginthreadex (Null,0,fun, (void*) i,0,null);
- SetEvent (G_hthreadevent[0]);
- WaitForMultipleObjects (Thread_num,hdl,true,infinite);
- For (i = 0; i < thread_num; i++)
- {
- CloseHandle (Hdl[i]);
- CloseHandle (G_hthreadevent[i]);
- }
- return 0;
- }
- unsigned int __stdcall fun (void *ppm)
- {
- int num = (int) PPM;
- int i = 0;
- For (i = 0; i< loop;i++)
- {
- WaitForSingleObject (G_hthreadevent[num],infinite);
- //printf ("Thread id=%d, thread number is%c,%d \ n", GetCurrentThreadID (), num+ ' A ');
- printf ("%c", num+' A ');
- if (num+1 = = thread_num)
- printf ("\ n");
- SetEvent (g_hthreadevent[(num+1)%thread_num]);
- }
- return 0;
- }
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