[英]Ada pass limited private type to task
我遇到一種情況,我想給任務提供有限的私有類型,以便它可以調用各種函數(特別是它是GNAT.Serial_Communications
的串行端口)。 我似乎無法弄清楚如何使其工作。
我嘗試過直接傳遞它,直到我必須使用該類型為止,它都可以正常工作,此時我無法將其復制到保存的變量中:
task body MyTask is
MyT : LPType;
begin
accept MyEntry (t : LPType) do
MyT := t; -- not valid, LPType is limited private
end MyEntry;
-- Later I do something using MyT
end MyTask;
既然那行不通,我嘗試將訪問權限傳遞給受限的私有類型,但是不幸的是,由於訪問的局限性,這仍然行不通:
procedure MyProcedure is
MyT : aliased LPType;
Task : MyTask;
begin
Initialize (MyT);
Task.MyEntry (MyT'Access);
end MyProcedure;
從技術上講,我使用Unrestricted_Access
對其進行了編譯,但這聽起來像是一種hack,根據我的經驗,當您使用hack繞過Ada中的編譯器時,編譯器有充分的理由迫使您執行此操作,並且您犯了一個錯誤。
所以我的問題是:是否可以通過條目將有限的私有類型傳遞給任務,或者這僅僅是個壞主意?
在Ada中, limited
關鍵字指示該類型沒有與之關聯的分配。 這與大多數主流語言完全相反,但考慮的是[物理]時鍾或RNG類型的東西:復制這些沒有意義,因此以這種方式對事物建模是有意義的。
但是,不能保證task
構造與調用其條目的線程在相同的內存空間中。 -所以我們在這里有點矛盾: limited
禁止復制,而entry
要求復制某種形式。
有幾種方法可以解決此問題,但是鑒於您提供的代碼段,解決方案是使task
成為limited
類型的組件。
Package Example is
Type LP is limited private;
Function Create return LP;
Function Create( Value : Integer ) return LP;
Procedure Print( Object : LP );
Private
Task Type Printer( Item : not null access LP ) is
Entry Print;
End Printer;
Type LP is limited record
Value : Integer := 100;
Task_Item : Printer(LP'Access);
end record;
end Example;
Package Body Example is
Function Create return LP is (others => <>);
Function Create( Value : Integer ) return LP is
(Value => Value, others => <>);
Procedure Print( Object : LP ) is
Begin
Object.Task_Item.Print;
end Print;
Task Body Printer is
Begin
accept Print do
Null;
end Print;
Ada.Text_IO.Put_Line( "Value:" & Integer'Image(Item.Value) );
End Printer;
end Example;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.