c++多线程编程(二)

这是道面试题目:有三个线程分别打印A、B、C,请用多线程编程实现,在屏幕上循环打印10次ABCABC…

见代码:

 1 #include <iostream>
 2 #include <Windows.h>
 3 
 4 using namespace std;
 5 
 6 HANDLE hMutex;
 7 int counts = 0;
 8 int flag = 3;
 9 
10 void t1();
11 void t2();
12 void t3();
13 
14 int main() {
15     HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)t1, NULL, 0, NULL);
16     hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)t2, NULL, 0, NULL);
17     hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)t3, NULL, 0, NULL);
18     hMutex = CreateMutex(NULL, FALSE, L"lvhuan");
19     CloseHandle(hThread);
20     while(counts<30){
21         Sleep(1000);
22     }
23     return 0;
24 }
25 void t1() {
26     while (counts < 30) {
27         WaitForSingleObject(hMutex, INFINITE);
28         if (flag == 3) {
29             flag = 1;
30             cout << 'A' << endl;
31             counts++;
32         }
33         ReleaseMutex(hMutex);
34     }
35 }
36 void t2() {
37     while (counts < 30) {
38         WaitForSingleObject(hMutex, INFINITE);
39         if (flag == 1) {
40             flag = 2;
41             cout << 'B' << endl;
42             counts++;
43         }
44         ReleaseMutex(hMutex);
45     }
46 }
47 void t3() {
48     while (counts < 30) {
49         WaitForSingleObject(hMutex, INFINITE);
50         if (flag == 2) {
51             flag = 3;
52             cout << 'C' << endl;
53             counts++;
54         }
55         ReleaseMutex(hMutex);
56     }
57 }

这里给个java版本的链接:http://mouselearnjava.iteye.com/blog/1949228?utm_source=tuicool&utm_medium=referral

原文地址:https://www.cnblogs.com/jiu0821/p/5255331.html