64,648
社区成员
发帖
与我相关
我的任务
分享
//
// fruit.cpp
// ~~~~~~~~~~~~~~~~
//
// @author <zhuxueling@pica.com>
// @data 2009-02-09
#include <string>
#include <iostream>
#include "Thread.hpp"
using namespace Traxex;
enum Fruit{ None, Apple, Orange};
class Plate{
public:
void add( std::string name, Fruit f){
while( true){
c_eat.wait();
std::cout << name << "\tadd\t";
if( f == Apple){
std::cout << "an Apple\n"; c_apple.signal(); Sleep( 1);
}else{
std::cout << "an Orange\n";c_orange.signal(); Sleep( 0.8);
}
}
}
void eat( std::string name, Fruit f){
while( true){
if( f == Apple) c_apple.wait();
else c_orange.wait();
std::cout << name << "\teat\t";
if( f == Apple) std::cout << "an Apple\n";
else std::cout << "an Orange\n";
Sleep( 0.9);
c_eat.signal();
}
}
void init(){
c_eat.signal();
c_eat.signal();
}
private:
Cond c_apple;
Cond c_orange;
Cond c_eat;
};
int main(){
Plate plate;
Thread father ( plate, &Plate::add, std::string("father"), Apple);
Thread mother ( plate, &Plate::add, std::string("mother"), Orange);
Thread boy_a ( plate, &Plate::eat, std::string("boy_a" ), Orange);
Thread boy_b ( plate, &Plate::eat, std::string("boy_b" ), Orange);
Thread girl_a ( plate, &Plate::eat, std::string("girl_a"), Apple);
Thread girl_b ( plate, &Plate::eat, std::string("girl_b"), Apple);
//start
father.start(); mother.start();
boy_a.start(); boy_b.start();
girl_a.start(); girl_b.start();
//init
Sleep( 1);
plate.init();
//join
father.join(); mother.join();
boy_a.join(); boy_b.join();
girl_a.join(); girl_b.join();
}