多线程问题

问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。[注:C语言选手可使用WINDOWS SDK库函数]
接口说明:
void init();  //初始化函数
void Release(); //资源释放函数
unsignedint__stdcall ThreadFun1(PVOID pM)  ; //线程函数1,传入一个int类型的指针,用于初始化输出A次数,资源需要线程释放
unsignedint__stdcall ThreadFun2(PVOID pM)  ;//线程函数2,无参数传入
unsignedint__stdcall ThreadFun3(PVOID pM)  ;//线程函数3,无参数传入
Unsigned int __stdcall ThreadFunc4(PVOID pM);//线程函数4,无参数传入

char  g_write[1032]; //线程1,2,3,4按顺序向该数组赋值。

#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;

char g_write[1032];
int num=0;
int iLoop=0;
HANDLE GetThreadEve[4];
HANDLE hThread[4];

unsigned int __stdcall ThreadFun1(PVOID pM)
{     
	int M=*(int *)pM;         
	iLoop=M;   
	while(M!=0)
	{
		WaitForSingleObject(GetThreadEve[0],INFINITE);
		g_write[num]='A';
		num++;
		SetEvent(GetThreadEve[1]);
		M--;
	}
	_endthreadex(0);
	return 0;
}
unsigned int __stdcall ThreadFun2(PVOID pM)
{
	for (int i=0;i<iLoop;i++)
	{
		WaitForSingleObject(GetThreadEve[1],INFINITE);
		g_write[num]='B';
		num++;
		SetEvent(GetThreadEve[2]);
	}
	_endthreadex(0);
	return 0;
}
unsigned int __stdcall ThreadFun3(PVOID pM)
{
	for (int i=0;i<iLoop;i++)
	{
		WaitForSingleObject(GetThreadEve[2],INFINITE);
		g_write[num]='C';
		num++;
		SetEvent(GetThreadEve[3]);
	}
	_endthreadex(0);
	return 0;
}
unsigned int __stdcall ThreadFun4(PVOID pM)
{
	for (int i=0;i<iLoop;i++)
	{
		WaitForSingleObject(GetThreadEve[3],INFINITE);
		g_write[num]='D';
		num++;
		SetEvent(GetThreadEve[0]);
	}
	_endthreadex(0);
	return 0;
}
void init()
{
	GetThreadEve[0] = CreateEvent(NULL,FALSE,TRUE,NULL);
	GetThreadEve[1] = CreateEvent(NULL,FALSE,FALSE,NULL);
	GetThreadEve[2] = CreateEvent(NULL,FALSE,FALSE,NULL);
	GetThreadEve[3] = CreateEvent(NULL,FALSE,FALSE,NULL);
	memset(g_write,NULL,sizeof(g_write));
}
void Release()
{
	CloseHandle(hThread[0]);
	CloseHandle(hThread[1]);
	CloseHandle(hThread[2]);
	CloseHandle(hThread[3]);
}
int main()
{
	int Num;
	cin>>Num;
	int *N=NULL;
	init();
    N=(int*)malloc(sizeof(int));
	*N=Num;
	hThread[0]=(HANDLE)_beginthreadex(NULL,0,ThreadFun1,N,0,NULL);
	hThread[1]=(HANDLE)_beginthreadex(NULL,0,ThreadFun2,NULL,0,NULL);
	hThread[2]=(HANDLE)_beginthreadex(NULL,0,ThreadFun3,NULL,0,NULL);
	hThread[3]=(HANDLE)_beginthreadex(NULL,0,ThreadFun4,NULL,0,NULL);
	WaitForMultipleObjects(4,hThread,TRUE,INFINITE);
	Release();
	cout<<g_write<<endl;
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值