码迷,mamicode.com
首页 > 编程语言 > 详细

开启3个线程依次打印ABC10次

时间:2015-05-06 23:00:56      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:c++   程序员   面试   

题目:

编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC.依次递推。



#include <stdio.h> 
#include <windows.h>  
#include<iostream>
#include <process.h>  
#include <time.h>
using namespace std;

HANDLE g_a, g_b, g_c;
CRITICAL_SECTION g_cs;

unsigned int __stdcall PrintA(void* pM)
{
	int i = 0;
	while (i < 10)
	{
		WaitForSingleObject(g_a, INFINITE);
		EnterCriticalSection(&g_cs);
		cout <<i+1<< ": A";
		SetEvent(g_b);
		++i;
		LeaveCriticalSection(&g_cs);		
	}
	return 0;
}

unsigned int __stdcall PrintB(void* pM)
{
	int i = 0;
	while (i < 10)
	{
		WaitForSingleObject(g_b, INFINITE);
		EnterCriticalSection(&g_cs);
		cout << 'B';
		SetEvent(g_c);
		++i;
		LeaveCriticalSection(&g_cs);
	}
	return 0;
}

unsigned int __stdcall PrintC(void* pM)
{
	int i = 0;
	while (i < 10)
	{
		WaitForSingleObject(g_c, INFINITE);
		EnterCriticalSection(&g_cs);
		cout << "C\n";
		SetEvent(g_a);
		++i;
		LeaveCriticalSection(&g_cs);
	}
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	InitializeCriticalSection(&g_cs);
	g_a = CreateEvent(NULL, FALSE, TRUE, NULL);
	g_b = CreateEvent(NULL, FALSE, FALSE, NULL);
	g_c = CreateEvent(NULL, FALSE, FALSE, NULL);
	HANDLE threads[3];

	threads[0] = (HANDLE)_beginthreadex(NULL, 0, PrintA, NULL, 0, NULL);
	threads[1] = (HANDLE)_beginthreadex(NULL, 0, PrintB, NULL, 0, NULL);
	threads[2] = (HANDLE)_beginthreadex(NULL, 0, PrintC, NULL, 0, NULL);

	WaitForMultipleObjects(3, threads, TRUE, INFINITE);

	CloseHandle(g_a);
	CloseHandle(g_b);
	CloseHandle(g_c);
	CloseHandle(threads[0]);
	CloseHandle(threads[1]);
	CloseHandle(threads[2]);
	DeleteCriticalSection(&g_cs);


	cout << endl;
	system("pause");
	return 0;
}


开启3个线程依次打印ABC10次

标签:c++   程序员   面试   

原文地址:http://blog.csdn.net/bupt8846/article/details/45541723

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!