实现一个队列。
队列的应用场景为:
一个生产者线程将int类型的数入列,一个消费者线程
将int类型的数出列
思路:这道题目,思路倒不是最重要的。想要测验的主要是多线程相关的基本操作。这方面,我现在不是特别熟悉,而且在网上这了下,有种说法是,多线程要考虑到不同的平台,比如在windows和linux上的多线程实现是不同的。所以,我觉的在我现在的阶段还是先不考虑具体的语法细节。因为,思路是不变的,而细节有可能会随着技术的发展而变化。
贴上网上转来的代码(我也没有跑,不知道行不行):
/*==============================================*\
34.(队列)
实现一个队列。
队列的应用场景为:
一个生产者线程将int类型的数入列,一个消费者线程
将int类型的数出列
\*==============================================*/
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>
#include <queue>
using namespace std;
HANDLE ghSemaphore; //信号量
const int gMax=100;//生产(消费)总数
std::queue<int> q; //生产入队,消费出队
//生产者线程
unsigned int __stdcall producerThread(void* pParam)
{
int n=0;
while(++n<=gMax)
{
//生产
q.push(n);
cout<<"produce"<<n<<endl;
ReleaseSemaphore(ghSemaphore,1,NULL);//增加信号量
Sleep(300);//生产间隔的时间,可以和消费间隔时间一起调节
}
_endthread();//生产结束
return 0;
}
//消费者线程
unsigned int __stdcall customerThread(void* pParam)
{
int n=gMax;
while(n--)
{
WaitForSingleObject(ghSemaphore,10000);
//消费
q.pop();
cout<<"custom "<<q.front()<<endl;
Sleep(500);//消费间隔的时间,可以和生产间隔时间一起调节
}
//消费结束
CloseHandle(ghSemaphore);
cout << "working end." << endl;
_endthread();
return 0;
}
void threadWorking()
{
ghSemaphore=CreateSemaphore(NULL,0,gMax,NULL);//信号量来维护线程同步
cout << "working start." << endl;
unsigned threadID;
HANDLE handles[2];
handles[0]=(HANDLE)_beginthreadex(
NULL,
0,
producerThread,
nullptr,
0,
&threadID);
handles[1]=(HANDLE)_beginthreadex(
NULL,
0,
customerThread,
nullptr,
0,
&threadID);
WaitForMultipleObjects(2,handles,TRUE,INFINITE);
}
int main()
{
threadWorking();
getchar();
return 0;
}