Filòsof 1

text/x-erlang filosof1.erl — 1.6 KB

Continguts del fitxer

-module(filosof1).
-export([dinar/0, initSem/0, lliure/0, ocupat/1]).

 
% Implementació del semafor
initSem() ->
	lliure().

ocupat(Pid) ->
	receive	
		{signal, Pid} -> lliure()
	end.	

lliure() ->
	receive
		{wait, Pid} ->
			Pid! ok,
			ocupat(Pid);
		stop -> finalitzar()
	end.

finalitzar() ->
	receive
		{wait, Pid} ->
			exit(Pid, kill),
			finalitzar()
		after	
			0 -> ok
	end.

signal() ->
	mutex!{signal, self()},
	ok.

wait() ->
	mutex!{wait, self()},
	receive
		ok -> ok
	end.
stop() -> mutex!stop.
	
		
esperaFinal(1) ->
	receive
 		final -> io:format("No queda cap filosof ~n")
 	end;

esperaFinal(N) ->
	receive
 		final -> 
			io:format("Queden ~p filosofs~n", [N-1]),
			esperaFinal(N-1)		
 	end.

filosof(_Num, Nom, 0, Pid) -> 	
	io:format("~s marxa.~n", [Nom]),
	Pid!final,
	ok;
 
filosof(Num, Nom, Cycle, Pid) ->
	io:format("~s està pensant.~n", [Nom]),
	timer:sleep(rand:uniform(1000)),
 
	io:format("~s te gana.~n", [Nom]),
	wait(),
	io:format("~s està menjant ******************.~n", [Nom]),
	timer:sleep(rand:uniform(1000)),
	signal(),
	io:format("~s ha deixat de menjar.~n", [Nom]),
	filosof(Num, Nom, Cycle-1, Pid).
 

dinar() ->	
		register(mutex, spawn(?MODULE, initSem, [])),
		N = 5,
		Cicles = 4,
		Pid = self(),
		spawn(fun()-> filosof(0, 'Aristotle', Cicles, Pid) end),
		spawn(fun()-> filosof(1, 'Kant', Cicles, Pid) end),
		spawn(fun()-> filosof(2, 'Spinoza', Cicles, Pid) end),
		spawn(fun()-> filosof(3, 'Marx', Cicles, Pid) end),
		spawn(fun()-> filosof(4, 'Russel', Cicles, Pid) end),
 		esperaFinal(N),
		io:format("Menjador tancat.~n"),
		stop().