Вы находитесь на странице: 1из 21

3.

: ,

3.1.
3.2.
3.2.1.
3.2.2.
3.2.2.1.
3.2.2.2.
3.2.2.3.

3.3.


,
()
.

,

.


( ),

.


.
(race conditions) .

X
Y

void echo ()
{
char in;
input ( in ) ;
output ( in ) ;
}

input(in);

output(in);

input(in);
output(in);

Y
Y


,
,
, .

(deadlocks)
()

, -

.


-
, .

(Deadlocks)
B

A
4

STOP

STOP

,
. ,
.


,
.

,
Down ( S ) P ( S ) Proberen ()
Up ( S ) V ( S ) Verhogen ()

,
1.
1
int semaphore;

down ( semaphore ) ;
/*
1*/

up ( semaphore ) ;

2
int semaphore;

down ( semaphore ) ;
/*
2*/

up ( semaphore ) ;



,
.

,

(
)

:
send ( destination, message )
receive ( source, message )



send/receive
send/receive


(ID )
( , )



1.

2.
3.


(
)



#define N 5
void philosopher ( int i )
{
while (TRUE)
{
think () ;
take_fork ( i ) ;
take_fork ( ( i + 1 ) % N ) ;
eat () ;
put_fork ( i ) ;
put_fork ( ( i + 1 ) % N ) ;
}
return;
}



#
#
#
#
#
#

define
define
define
define
define
define

N 5
LEFT ( i 1 ) % N
RIGHT ( i + 1 ) % N
THINKING 0
HUNGRY 1
EATING 2

typedef int semaphore ;


int state [ N ] ;
semaphore mutex = 1 ;
semaphore s [ N ] ;



void philosopher ( int i )
{ while ( TRUE )
{
think () ;
take_forks ( i ) ;
eat ();
put_forks ( i ) ;
}
}
void put_forks ( int i )
{
down ( & mutex ) ;
state[i] = THINKING ;
test ( LEFT ) ;
test ( RIGHT ) ;
up ( & mutex ) ;
}

void take_forks ( int i )


{
down ( & mutex ) ;
state [ i ] = HUNGRY ;
test ( i ) ;
up( & mutex ) ;
down ( & s [ i ] ) ;
}
void test ( int i )
{
if ( ( state [ i ] == HUNGRY )
&& ( state [ LEFT ] != EATING )
&& ( state [ RIGHT ] != EATING ))
{
state [ i ] = EATING ;
up ( & s [ i ] ) ;
}
}


( )

typedef int semaphore ;


int rc = 0 ;
semaphore mutex = 1 ;
semaphore db = 1 ;
void reader ( void )
void writer ( void )
{
{
while ( TRUE )
while ( TRUE )
{
{
down ( & mutex ) ;
think_up_data () ;
rc++ ;
down ( & db ) ;
if ( rc == 1 ) down ( & db ) ;
write_data_base () ;
up ( & mutex ) ;
up ( & db ) ;
read_data_base () ;
down ( & mutex ) ;
}
rc ;
}
if ( rc ==0 ) up ( & db ) ;
up ( & mutex ) ;
use_data_read () ;
}
}


(-
)

#define CHAIRS 5
typedef int semaphore ;
semaphore customers = 0 ;

semaphore barbers = 0 ;
semaphore mutex = 1 ;
int waiting = 0 ;

void barber ( void )


void customer ( void )
{
{
down ( & mutex ) ;
while ( TRUE )
if ( waiting < CHAIRS )
{
{
down ( & customers ) ;
waiting = waiting + 1 ;
down ( & mutex ) ;
up ( & customers ) ;
waiting = wating 1 ;
up ( & mutex ) ;
up ( & barbers ) ;
down ( barbers ) ;
up ( & mutex ) ;
get_haircut () ;
cut_hair () ;
}
else
}
{
}
up ( & mutex ) ;
}
}

Вам также может понравиться