2011-04-01 42 views
1

我正在實施一個停車場,有2個入口門和1個可以離開公園的停車場。對我來說,一切都看起來不錯,但我得到這樣的錯誤過程創建問題

Error in process <0.84.0> with exit value: {badarg,[{parking,car,2},{random,uniform,0}]} 

我的代碼是:

-module (parking2). 
-export ([start/3]). 
-export ([car/2, parkingLoop/1]). 

carsInit(0, _Iterations) -> 
    ok; 
carsInit(Number, Iterations) -> 
    spawn(parking, car, [Number, Iterations]), 
    carsInit(Number - 1, Iterations). 

car(_ID, 0) -> 
    ok; 
car(ID, Iterations) -> 
    Gate = random:uniform(2), 
    parking ! {enter, self()}, 
    receive 
     error -> 
      io:format("Car ~B ncanot enter - there is no free place.~n", [ID]), 
      Time = random:uniform(1000), 
      timer:sleep(Time), 
      car(ID, Iterations); 
     ok -> 
      io:format("Car ~B entered through the ~B gate~n", [ID, Gate]) 
    end, 
    StopTime = random:uniform(500) + 500, 
    timer:sleep(StopTime), 
     parking ! {leave, self(), ID}, 
     FreerideTime = random:uniform(1000) + 500, 
    timer:sleep(FreerideTime), 
    car(ID, Iterations - 1). 

parkingInit(Slots) -> 
    spawn(parking, parkingLoop, [Slots]). 

parkingLoop(Slots) -> 
    receive 
     {enter, Pid} -> 
      if Slots =:= 0 -> 
       Pid ! error 
      end, 
      Pid ! ok, 
      parkingLoop(Slots - 1); 
     {leave, Pid, ID} -> 
      io:format("Car ~B left the car park.", [ID]), 
      parkingLoop(Slots + 1); 
     stop -> 
      ok 
    end.  


start(Cars, Slots, Iterations) -> 
    parkingInit(Slots), 
    carsInit(Cars, Iterations). 

五月人幫助我嗎?我學了Erlang幾天,不知道,這裏有什麼問題。

由於提前, 拉狄克

回答

6

您發佈的示例使用了錯誤的模塊中的spawn/3電話:

spawn(parking, parkingLoop, [Slots]). 

應該更好地工作(或者至少提供一個更最新的錯誤)如果您將其更改爲:

spawn(?MODULE, parkingLoop, [Slots]). 

(務必使用?MODULE,這是計算結果爲CURREN宏t模塊名稱,當做這樣的事情,因爲它會避免使用錯誤的模塊比預期的很多錯誤)。

該錯誤來自未註冊parkingLoop進程。您正嘗試使用parking ! ...向其發送消息,但沒有任何過程被命名爲parking。更改行33:

register(parking, spawn(parking2, parkingLoop, [Slots])). 

(即使在這裏,你可以使用在未來?MODULE宏來避免問題:?MODULE ! ...register(?MODULE, ...)因爲你只有一個進程使用這個名稱)

此外,您if聲明在線38錯過了一條跌宕的條款。使它看起來像這樣來處理的情況下Slots等於零:

if 
    Slots =:= 0 ->Pid ! error; 
    true -> ok 
end, 

(該ok表達不會有任何影響,因爲不使用if語句的返回值)

+1

謝謝你非常。 – Radek 2011-04-01 14:59:36

+0

對不起,我問,但如何做到這一點? – Radek 2011-04-04 21:19:03

+0

啊,沒問題! :-)只需點擊答案左側的答案選項下方的綠色複選框(歡迎來到Stack Overflow!) – 2011-04-05 08:28:47