#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環境下編寫,測試通過
//編譯多線程的程序時的系統參數設置我想妳應該知道