阿达 TASKING_ERROR

Ada TASKING_ERROR

假设以下情况: 有一个盒子,是用来存放硬币的 人们从盒子里拿钱 人们把钱放进盒子里 我将任务条目作为添加、减去、读取和写入。下面是我的代码。现在我很困惑如何调用条目添加、减去和读取来实现上述要求,请帮助

with Ada.Text_IO,ada.integer_text_io;
use ada.text_io,ada.integer_text_io;

procedure protected_imp is
   task type box(initial_value:integer;min_value:integer;max_value:integer) is
      entry add(number:integer); 
      entry subtract(number:integer);
      entry read;
   end box;
   task body box is 
      x:integer:=initial_value; --shared variable
   begin
      loop                  --why raised TASKING_ERROR when loop is removed?
         select
            when x<max_value=>
               accept add(number:integer)do
                  x:=x+number;
               end add;
         or  
            when x>min_value=>
               accept subtract(number:integer) do
                  x:=x-number;
               end subtract;
         or
            accept read do
               put("coins");
               put_line(integer'image(x));
            end read;
         or
            delay(5.0);
            put("no request received for 5 seconds");
         end select;
      end loop;
   end box;
   go:box(1,0,10);
begin ----- how to call? and why  i am getting "no request received for 5 seconds " even i have activate go .add(1) ?
   for i in 1..5 loop
      go.add(1);
   end loop;
   go.read;
end protected_imp;

在这里,您的程序产生输出

$ ./protected_imp 
coins 6
no request received for 5 secondsno request received for 5 secondsno request received for 5 seconds^C

(当时我停止了)。

“coins 6”正是它应该给出的输出;您已将 1 添加到起始值 (1) 5 次。

如果你删除循环,你得到 Tasking_Error 的原因是任务执行一次 select 语句;在接受 go.add 调用后,它退出 select 并退出任务底部,因此下一个 go.add 调用无处可去,因为不再有任务。

事件的顺序是

task arrives at select; all the alternatives are closed
main calls go.add (1)'
task accepts the entry, increments x, exits the select, and goes round the loop again to wait at the select
main calls go.add (1)
task accepts the entry, increments x, exits the select, and goes round the loop again to wait at the select
main calls go.add (1)
task accepts the entry, increments x, exits the select, and goes round the loop again to wait at the select
main calls go.add (1)
task accepts the entry, increments x, exits the select, and goes round the loop again to wait at the select
main calls go.add (1)
task accepts the entry, increments x, exits the select, and goes round the loop again to wait at the select
main calls go.read
task accepts the entry, prints out “coins 6”, and goes round the loop again to wait at the select
main finishes and waits until the task terminates, which it doesn’t, because
after 5 seconds, the select’s delay alternative opens, so the task takes it, prints the message (it should really use Put_Line) and goes round the loop again to wait at the select
after 5 seconds, the select’s delay alternative opens, so the task takes it, prints the message and goes round the loop again to wait at the select
...