📄 onewriteronereader.cpp
字号:
#include <stdio.h>
#include "CMcl.h"
class CPrimeList {
private:
// ten thousand primes is enough for
// our purposes...
enum {MAX_PRIMES = 10000};
int m_nPrimes;
unsigned m_aPrimes[MAX_PRIMES];
public:
CPrimeList() {
m_nPrimes = 0;
};
inline void AddPrime(unsigned uPrime) {
// prevent overflowing the array...
if (m_nPrimes == MAX_PRIMES)
return;
// add the prime to our list...
m_aPrimes[m_nPrimes] = uPrime;
m_nPrimes++;
};
inline int GetPrimeCount(void) {
return m_nPrimes;
};
inline unsigned GetPrime(int iIndex) {
return m_aPrimes[iIndex];
};
};
class CPrimeConsumer : public CMclThreadHandler {
private:
BOOL m_bContinue;
CPrimeList *m_pcpl;
public:
CPrimeConsumer(CPrimeList *pcpl) {
m_pcpl = pcpl;
m_bContinue = TRUE;
};
void Stop() {
m_bContinue = FALSE;
};
unsigned ThreadHandlerProc(void) {
int last = 0;
while (m_bContinue) {
// sleep for 1 second...
::Sleep(1000);
// print all the primes that have been
// computed since the last time we printed...
int index;
int limit = m_pcpl->GetPrimeCount();
for (index = last; index < limit; index++) {
// print the prime...
printf( "%8u", m_pcpl->GetPrime(index));
// newline every 10 primes...
if ((index % 10) == 9) {
printf( "\n");
}
}
last = limit;
}
return 0;
}
};
class CPrimeProducer : public CMclThreadHandler {
private:
BOOL m_bContinue;
CPrimeList *m_pcpl;
public:
CPrimeProducer(CPrimeList *pcpl) {
m_pcpl = pcpl;
m_bContinue = TRUE;
};
void Stop() {
m_bContinue = FALSE;
};
unsigned ThreadHandlerProc(void) {
// add two to our prime list...
m_pcpl->AddPrime(2);
// only check odd numbers...
unsigned num = 3;
// compute primes until we are told to stop...
while (m_bContinue) {
// check if the current number is evenly divided
// by any prime that we have already found...
int index;
int limit = m_pcpl->GetPrimeCount();
for (index = 0; index < limit; index++) {
if ((num % m_pcpl->GetPrime(index)) == 0) {
break;
}
}
// we tested all of the primes...
if (index == limit) {
m_pcpl->AddPrime(num);
}
// check the next odd number...
num += 2;
}
return 0;
}
};
int main( int argc, char *argv[]) {
// object for storing primes...
CPrimeList cpList;
// initialize producer/consumer thread handlers...
CPrimeProducer cthProducer(&cpList);
CPrimeConsumer cthConsumer(&cpList);
// create the threads...
CMclThreadAutoPtr ctapProducer = new CMclThread(&cthProducer);
CMclThreadAutoPtr ctapConsumer = new CMclThread(&cthConsumer);
// run for 5 seconds...
Sleep(5000);
// tell the consumer to stop...
cthProducer.Stop();
// tell the producer to stop...
cthConsumer.Stop();
// wait for the threads to exit...
ctapProducer->WaitForTwo( *ctapConsumer, TRUE, INFINITE);
printf( "\nAll done.\n");
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -