全国科技系统先进集体:求助:编程高手请进!

来源:百度文库 编辑:中科新闻网 时间:2024/05/02 13:06:31
用C或C++或JAVA语言编写一个应用程序:其中创建两个子线程,一个生产者线程,一个消费者线程,使用一个共享数组实现二者之间的数据交换。生产者线程产生随机数并存入共享数组;消费者线程从共享数组中取出随机数,将其输出到一个磁盘文件,并计算输出这些随机数的平均值.

#include "process.h"
#include "time.h"
#include "conio.h"
#include "iostream"
using namespace std;

class block //自定义一个简单的信号量类,防止数组共享冲突
{
public:
block():m_bBlocked(false){};
void SetBlock()//
{
while (m_bBlocked) ;
m_bBlocked = true;
};
void Reset()
{
m_bBlocked = false;
};
private:
bool m_bBlocked;
};

const int N = 10; //你可以定义自己的数组大小
const char *path = "d:\\test.txt";
bool stop = false; //线程控制量
bool haveContent = false; //数组是否有内容,即生产者是否生产新产品
block blk; //共享信号量

int random[N];
void producer(void * = NULL);//生产者线程
void customer(void * = NULL);//消费者线程
void sleep(int); //间隔时间,不然系统要忙死

int main()
{
_beginthread(producer,0,NULL);
_beginthread(customer,0,NULL);
while(!getch());
stop = true;
return 0;
}

void producer(void * /* = NULL */)
{
srand((unsigned)time(NULL));
while (!stop)
{
if(haveContent)
continue;

blk.SetBlock();
for(int i = 0;i<N;i++)
random[i] = rand();
haveContent = true;
sleep(1000);

blk.Reset();
}
}
void customer(void * /* = NULL */)
{
while (!stop)
{
int a[N];
if(!haveContent)
continue;

blk.SetBlock();

for(int i=0;i<N;i++)
{
printf("%-7d",random[i]);
a[i]=random[i];
}
cout<<endl;
haveContent = false;

blk.Reset();

FILE *pFile;
pFile = fopen(path,"a+");
for(int j=0;j<N;j++)
fprintf(pFile,"%-7d",a[j]);
fprintf(pFile,"\n");
fclose(pFile);

}
}

void sleep(int time)
{
for(int i=0;i<time*10;i++)
for(int j=0;j<50000;j++);
}
//以上在VC6.0环境下编写,测试通过
//编译多线程的程序时的系统参数设置我想你应该知道

好象不太难耶