/*
 * NMSTL, the Networking, Messaging, Servers, and Threading Library for C++
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <iostream>

#include <nmstl/tqueue>

using namespace nmstl;
using namespace std;

tqueue<unsigned int> inputs;

// Performs a sieve of Erasthones to see if a number is
// prime or not.
class sieve_thread : public thread {
  public:
    void run() {
	while (1) {
	    cout << *this << ": Waiting." << endl;
	    unsigned int input;
	    if (!inputs.wait(input)) {
		cout << *this << ": Terminating." << endl;
		break;
	    }

	    cout << *this << ": Chewing on input " << input << endl;

	    bool *composite = new bool[input];
	    for (unsigned int i = 0; i <= input; ++i)
		composite[i] = 0;

	    bool is_prime = true;
	    for (unsigned int i = 2; i < input; ++i) {
		if (!composite[i]) {
		    unsigned int j;
		    for (j = i + i; j < input; j += i)
			composite[j] = true;
		    if (j == input) {
			is_prime = false;
			break;
		    }
		}
	    }

	    delete[] composite;

	    // pretend like it took a long time
	    thread::sleep(ntime::msecs(input));

	    cout << *this << ": the number " << input << " is " <<
		(is_prime ? "prime" : "composite") << endl;
	}
    }
};

int main() {
    cout << "Enter a number and I'll tell you if it's prime.  (0 to end)" << endl;
    cout << endl;
    cout << "(For instance, try typing the numbers 5000 through 5010 in rapid succession.)" << endl;

    sieve_thread sieves[5];
    for (int i = 0; i < 5; ++i)
	sieves[i].start();

    unsigned int num;
    while (true) {
	if (!(cin >> num))
	    break;
	if (num == 0)
	    break;
	inputs.push(num);
	cout << "- there are " << inputs.size() << " elements queued" << endl;
    }

    cout << "That's all folks!" << endl;
    inputs.close();
    for (int i = 0; i < 5; ++i)
	sieves[i].join();
}
