Universidad de Costa Rica
Escuela de Ciencias de la Computación e Informática
CI-0122 Sistemas operativos
Ejemplos
|
|
|
CI0122 /
Ejemplos
/ 2014-i |
// threadtest.cc
// Simple test case for the threads assignment.
//
// Create two threads, and have them context switch
// back and forth between themselves by calling Thread::Yield,
// to illustratethe inner workings of the thread system.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "synch.h"
#include <iostream>
using namespace std;
//----------------------------------------------------------------------
// SimpleThread
// Loop 5 times, yielding the CPU to another ready thread
// each iteration.
//
// "which" is simply a number identifying the thread, for debugging
// purposes.
//----------------------------------------------------------------------
Semaphore c("SemaforoC",0);
Semaphore m("SemaforoM",0);
int ms = 0;
int cs = 0;
void
SimpleThread(int which)
{
int num;
if(which == 0){
cout << "Soy misionero" << endl;
if(ms >= 1 && cs >= 1){
m.V();
c.V();
ms -= 1;
cs -= 1;
cout << "Cruzar!!!" << endl;
cout<<"misioneros esperando = "<<ms<<endl;
cout<<"canibales esperando = "<<cs<<endl;
}else if(ms >= 2){
m.V();
m.V();
ms -= 2;
cout << "Cruzar!!!" << endl;
cout<<"misioneros esperando = "<<ms<<endl;
cout<<"canibales esperando = "<<cs<<endl;
}else{
ms++;
m.P();
}
}else{
cout << "Soy canibal" << endl;
if(ms >= 2){
m.V();
m.V();
ms -= 2;
cout << "Cruzar!!!" << endl;
cout<<"misioneros esperando = "<<ms<<endl;
cout<<"canibales esperando = "<<cs<<endl;
}else if(cs >= 2){
c.V();
c.V();
cs -= 2;
cout << "Cruzar!!!" << endl;
cout<<"misioneros esperando = "<<ms<<endl;
cout<<"canibales esperando = "<<cs<<endl;
}else{
cs++;
c.P();
}
}
/*if((ms>=2)&&(cs>=1)){
ms -= 2;
cs -= 1;
s.V();
}else if (ms>=3){
ms-=3;
s.V();
}else if(cs>=3){
cs -= 3;
s.V();
}else{
s.P();
cout << "Cruzar!!!" << endl;
cout<<"misioneros esperando = "<<ms<<endl;
cout<<"canibales esperando = "<<cs<<endl;
}*/
}
//----------------------------------------------------------------------
// ThreadTest
// Set up a ping-pong between two threads, by forking a thread
// to call SimpleThread, and then calling SimpleThread ourselves.
//----------------------------------------------------------------------
void
ThreadTest()
{
int random;
DEBUG('t', "Entering SimpleTest");
int i;
for(i = 1; i < 15; ++i){
random = Random()%2;
char name[100];
sprintf(name,"O %d",random);
Thread *t = new Thread(name);
t->Fork(SimpleThread, random);
}
SimpleThread(0);
}