具体而言,任务是否有办法获取自身的引用?
例如:
task type someTask;
type someTaskAccessor is access someTask;
task body someTask is
pointerToTask : someTaskAccessor;
begin
pointerToTask = this;
end someTask;
具体而言,任务是否有办法获取自身的引用?
例如:
task type someTask;
type someTaskAccessor is access someTask;
task body someTask is
pointerToTask : someTaskAccessor;
begin
pointerToTask = this;
end someTask;
包Ada.Task_Identification提供了Current_Task函数,用于检索当前任务的任务ID。
task type someTask;
type someTaskAccessor is access someTask;
task body someTask is
-- Initialize the access type variable as pointing to the same task it's declared in.
pointerToTask : someTaskAccessor := someTask'Unchecked_Access; --equiv to "this" ptr
begin
-- pointerToTask = this; --this is unneeded, pointerToTask is already set!
end someTask;
pointerToTask
应该被声明为 constant
。 - Simon Wright这里有几件事情。
首先,Ada和C++的面向对象方式不同。语言中没有“this”指针。调度是基于参数完成的。这意味着可以基于多个参数进行调度,与C++不同。这是另一个讨论的话题。如果您不喜欢它,您可以随时将调度参数命名为“this”。
其次,面向对象的概念并不适用于像任务这样的并发对象。这不是Ada的错。这是一个众所周知的问题。可悲的是,它被称为“并发问题”,因此在谷歌搜索中,与编程问题相关的参考资料会淹没它。基本要点是,您可以使对象支持继承、动态调度和所有好东西,或者您可以使它们支持并发。在同一语言结构中同时实现两者非常困难。
实际上,如果您需要指向自己任务的指针,您可以将其设置为全局变量,或者让分配它的任务使用某种初始化约会传递指针。我以前见过这样做的情况,当工作任务堆栈中的任务完成时,将自己放回“空闲”堆栈。
task type computer;
type computer_ptr is access all computer;
task type computer is
entry init(id:integer);
entry set_neighbor(left,right:computer_ptr);
end computer;
protected comp_list is
procedure insert; -- called by organizer
procedure remove(from:integer); -- called by task
private
type comp_list is array(integer range<>) of computer_ptr;
comps:comp_list(1..MAX):=(others=>null); -- or use own structure
end comp_list;
task body computer is
id_:integer;
left_n,right_n:computer_ptr:=null;
begin
accept init(id:integer) do
id_:=id;
end init;
while true loop
select
accept set_neighbor(left,right:computer_ptr) do
left_n:=left;right_n:=right;
end set_neighbor;
or
-- do its work
end select;
if (some_condition) then
comp_list.remove(id_);
break;
end if;
end loop;
end task computer;
protected body comp_list is
procedure insert is
p:computer_ptr;
begin
p:=new computer;
-- add to list -> nr;
p.all.init(nr);
-- call set_neighbor to its left and itself
end insert;
procedure remove(from: integer) is
begin
-- remove from list and get its neighbors
-- call set_neighbor regarding new ones
end remove;
end comp_list;