Task oriented programming?
От: chudo19  
Дата: 16.05.06 18:13
Оценка:
Как то нарвался на интересную реализацию coroutines или cooperative multitasking в одной игровой SDK
вот примерно такое на псевдо С++:


proc void Entity::Main(Entity target)
{
...
    //ждем окончания процедуры Attack попутно отлавливая сообщения пеердоваемые ей из шедулера
    Result res = wait_for(Attack(taget))
    {
      on(Damage)
      {  
          if(this.m_Health<10)
              //прервать Attack и все функции дальше по стеку и размотать стек вплоть до Main 
              //вернее насильно вызвать некий return handler
              break;
          else
              //продолжить исполнение Attack или того что вызвала Attack 
              resume;

      }
      on(EntityDead)
      {
          if(this.m_Target==EntityDead.m_Sender)
             // заменить Event EntityDead на NewTargetEvent который теперь получит процедура Attack и продолжить исполнение Attack             
             resume NewTargetEvent(FindNewTarget());
          else
             resume;
      }
      on(Return)
      {  
          // код в случае если кто то выше по стэку требует прерватся ("break")
         //some cleanup
      }
    }
...

}
//такие же фокусы для Attack
proc void Entity::Attack(Entity target)
{
...
if(some flag)
{
    wait_for(Time(max_time))
    {
      on(SeeEnemy)
      {  
         ....
              resume;

      }
      on(EntityDead)
      {
          ...
      }
    }
}
else
    wait_for(...)
...

}

//ну и так далее.


так вот вопрос.
не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
есть ли название такому способу програмирования?
существуют ли языки поддерживающие такую концепцию?
заранее благодарен.
Re: Task oriented programming?
От: vortex Украина  
Дата: 16.05.06 18:47
Оценка:
Здравствуйте, chudo19, Вы писали:

C>так вот вопрос.

C>не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
C>есть ли название такому способу програмированиhttp://rsdn.ru/Forum/message.1900776.aspxя?
C>существуют ли языки поддерживающие такую концепцию?
C>заранее благодарен.

очень похоже на реализацию конечного автомата.

доки тут

Из языков встроеная поддержка КА точно есть в PAWN
Re: Task oriented programming?
От: Quintanar Россия  
Дата: 16.05.06 18:49
Оценка:
Здравствуйте, chudo19, Вы писали:

C>так вот вопрос.

C>не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
C>есть ли название такому способу програмирования?
C>существуют ли языки поддерживающие такую концепцию?
C>заранее благодарен.

Continuation passing style (CPS). Есть в родном виде в scheme, например. Вроде в perl втроили, поскольку очень полезная вещь для веб серверов.
Re[2]: Task oriented programming?
От: chudo19  
Дата: 17.05.06 06:16
Оценка:
Здравствуйте, vortex, Вы писали:

V>очень похоже на реализацию конечного автомата.

вобщем то не похоже. нет даже явного способа переключить состояние. если и похоже то на HFSM.

V>доки тут


"интересные" вы ссылки даете
Re[2]: Task oriented programming?
От: chudo19  
Дата: 17.05.06 06:19
Оценка:
Здравствуйте, Quintanar, Вы писали:

Q>Continuation passing style (CPS). Есть в родном виде в scheme, например. Вроде в perl втроили, поскольку очень полезная вещь для веб серверов.

Почитал. дык вроде это для функциональных языкрв только. В общем тоже не совсем то.
Re: Task oriented programming?
От: FR  
Дата: 17.05.06 07:57
Оценка:
Здравствуйте, chudo19, Вы писали:


C>так вот вопрос.

C>не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
C>есть ли название такому способу програмирования?
C>существуют ли языки поддерживающие такую концепцию?

Так вроде такое легко делать на любом языке подерживающем оператор yield (итераторы из C# 2 или генераторы из питона)
Re[3]: Task oriented programming?
От: Quintanar Россия  
Дата: 17.05.06 09:37
Оценка:
Здравствуйте, chudo19, Вы писали:

Q>>Continuation passing style (CPS). Есть в родном виде в scheme, например. Вроде в perl втроили, поскольку очень полезная вещь для веб серверов.

C>Почитал. дык вроде это для функциональных языкрв только. В общем тоже не совсем то.

Нет, CPS абсолютно не функциональная вещь. В функциональных языках ее проще реализовать, потому что там есть closures, не более того.
Re[2]: Task oriented programming?
От: chudo19  
Дата: 17.05.06 10:25
Оценка:
Здравствуйте, FR, Вы писали:


FR>Так вроде такое легко делать на любом языке подерживающем оператор yield (итераторы из C# 2 или генераторы из питона)


легко.относительно.только вопрос не о реализации такой системы.
повторюсь:
не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
есть ли название такому способу програмирования?
Re[3]: Task oriented programming?
От: FR  
Дата: 17.05.06 10:38
Оценка:
Здравствуйте, chudo19, Вы писали:

C>Здравствуйте, FR, Вы писали:



FR>>Так вроде такое легко делать на любом языке подерживающем оператор yield (итераторы из C# 2 или генераторы из питона)


C>легко.относительно.только вопрос не о реализации такой системы.

C>повторюсь:
C>не встречал ли кто небудь научных работ или просто статей с описанием таких идей?
C>есть ли название такому способу програмирования?

Посмотри на http://www.softcraft.ru там были статьи по сопрограммам и автоматному программированию.
Re: Protocol Controlled Activities
От: Сергей Губанов Россия http://sergey-gubanov.livejournal.com/
Дата: 17.05.06 11:39
Оценка: -1
Здравствуйте, chudo19, Вы писали:

C>существуют ли языки поддерживающие такую концепцию?


Язык программирования называется Zonnon. Разрабатывается в ETH на деньги Microsoft.

Zonnon is a general-purpose programming language in the Pascal, Modula-2 and Oberon family. It retains an emphasis on simplicity, clear syntax and separation of concerns whilst focusing on concurrency and ease of composition and expression. Unification of abstractions is at the heart of its design and this is reflected in its conceptual model based on modules, objects, definitions and implementations. Zonnon offers a new computing model based on active objects with their interaction defined by syntax controlled dialogs. It also introduces new features including operator overloading and exception handling, and is specifically designed to be platform independent.

Там протокол диалога активностей прописывается в EBNF представлении. Фрагменты из сообщения об языке:

9.2 Protocol Controlled Activities

An activity can spawn another activity in the same, or a different, object or module. When this occurs
the two activities can share a formal protocol which governs the dialog of interaction between them
defined in the form of an EBNF syntax. Of course it is possible for a protocol to be null, in which case
there is no interaction specified. See also 5.3.4 Protocol types. A complete example of the use of
activities is presented in section 16 .
Zonnon Language Report: Release v03 r01 b35 Saved on 13 January 30 2006
Such activities are created and interact in the following way:

1. A protocol type is declared which defines the valid sequence of interaction between the
activities in the form of an EBNF syntax.

2. The first activity is instantiated within a module or object, it is referred to as the client.

3. The client activity then instantiates the second activity in a module or object, it is referred to
as the server. The client and the server both implement (share) the same protocol. The client
activity is always anonymous from the server’s viewpoint. The client references its server
using an variable of the activity’s type.

4. The two activities can now interact according to the EBNF syntax defined in the protocol they
share. This is achieved by using the client sending and receiving parameters to and from its
server; in turn the server accepts parameters from its client and returns parameters back to it.

5. The is operator can be used to discriminate between different types of syntactic tokens (see
6.2.4). The allowed types are integer, real, string, keywords (i.e. the enumerated tokens of the
protocol) and special characters.

6. The dialog is only ended when either of the two activities has terminated; either by reaching
the end of its begin … end body, or terminating due to trap to the system (catastrophic error).
A protocol controlled activity supports explicit synchronisation and communication with its client
activity; it may be declared in the scope of a different object or module. An activity may spawn another
activity in either the same or another object or module hence gaining access to its scope via parameters
passed according to the protocol.


16 Example of Protocol Controlled Activities and Dialog
Here is a longer example illustrating how a protocol can be used to control the dialogue between
activities. Within the EBNF protocol specifications the communication of an item from the server to
the client is prefixed by a ‘?’. The example implements the well known Simple Mail Transmission
Protocol SMTP used for email delivery.

definition {public} MailProtocols;
(* This provides the definition of the SMTP protocol to control the interaction between the activities*)

    protocol SMTP = ( (* defines the tokens used in the EBNF of the dialog *)
        SMTP_SERVER_READY, SERVICE_NOT_AVAILABLE, HELO,
        OK, MAIL_FROM, RCPT_TO,
        RCPT_REJECTED, DATA, START_MAIL_INPUT,
        END, QUIT, BYE,
        msg_body = DATA ?START_MAIL_INPUT { string } END ?OK,
        session = HELO string ?OK {mail_from rcpt_to {rcpt_to} msg_body},
        se_end = QUIT ?BYE,
        mail_from = MAIL_FROM string ?OK,
        rcpt_to = RCPT_TO string ( ?OK | ?RCPT_REJECTED
        SMPT = ?SMTP_SEVER_READY [session] se_end | ?SERVICE_NOT_AVAILABLE,);

end MailProtcols.


(* SMTP Mail Server activity which implements the server side of the protocol *)
object MailServer implements MailProtocols;
    
    activity SendMail implements MailProtocols.SMTP; (* associates the activity with the protocol type *)

        var request: SMTP; any_request: object;
        host, mfrom, mto, mtextline: string;

    begin
        return SMTP.SMTP_SERVER_READY;
        accept request;
        if request = SMTP.HELO then (* If not HELO then request is QUIT *)
            accept host;
            return OK; (* Confirm that client is accepted *)
            (* Sending a message *)
            loop
                accept request;
                if request = SMTP.QUIT then exit end;
                (* Protocol guarantees that request = SMTP.MAIL_FROM *)
                accept mfrom; (* Sender e-mail *)
                return OK; (* Confirm that sender is accepted *)
                (*** New mail - clearing recipients list ***)
                accept request;
                while request = SMTP.RCPT_TO do
                accept mto; (* One more recipient *)
                if (* checking the recipient is *) true then
                    return SMTP.OK (* Recipient accepted *)
                    (* Adding mto to the rcpt list *)
                else
                    return SMTP.RCPT_REJECTED (* Recipient rejected *)
                end;
                accept request
            end; (* Request can be SMTP.DATA or SMTP.QUIT *)
            if request = SMTP.QUIT then exit end;
            (* Protocol guarantees that request = SMTP.DATA *)
            return SMTP.START_MAIL_INPUT;
            accept any_request;
            while any_request is string do
                mtextline := string( request ); (* One more text line *)
                accept any_request;
            end; (* while *) (* any_request is SMTP.END *)
            (* Accept the lines of message until all received *)
            return OK
            (* Putting the message to the queue *)
        end (* loop *)
        return SMTP.BYE
    end (* of activity *) SendMail;
end (* of object *) MailServer.


(* SMTP MailClient activity which implements the client side of the protocol *)
object {public} MailClient;
    var {public} server: MailServer;
    
    procedure {public} Configure(server: MailServer)
    begin
        self.server := server;
    end Configure;

    procedure {public} SendMail;
        var smtp: activity { MailProtocols.SMTP };
        answer: MailProtocols.SMTP;
        i: integer;
    begin
        smtp := new server.SendMail; (* new dialog with the server *)
        answer := smtp();
        if answer = MailProtocols.SMTP.SMTP_SERVER_READY then
            answer := smtp( MailProtocols.SMTP.HELO, "www.roman.nnov.ru" );
            if answer = MailProtocols.SMTP.OK then
                for (* each mail in outbox *) i := 1 to 1 do
                    answer := smtp( MailProtocols.SMTP.MAIL_FROM, "roman.mitin@inf.ethz.ch" );
                    if answer = MailProtocols.SMTP.OK then
                        answer := smtp( MailProtocols.SMTP.RCPT_TO, "zueff@inf.ethz.ch" );
                        if answer = MailProtocols.SMTP.OK then
                            answer := smtp( MailProtocols.SMTP.DATA );
                            if answer = MailProtocols.SMTP.START_MAIL_INPUT then
                                smtp( "Hi!" );
                                smtp( "It works!" );
                                answer := smtp( MailProtocols.SMTP.END );
                                if answer = MailProtocols.SMTP.OK then
                                    answer := smtp( MailProtocols.SMTP.QUIT )
                                    if answer = MailProtocols.SMTP.BYE then
                                        (* Session closed *)
                                    end
                                    (* the following else parts would provide relevant error recovery *)
                                else (* SMTP.OK missing, out of sequence *)
                                end
                            else (* No invitation to input data *)
                            end
                        else (* Recipient has been rejected *)
                        end
                    else (* Sender has been rejected *)
                    end
                end (* for each mail in mailbox *)
            else (* Host has been rejected *)
            end
        else (* Can't connect, server not ready *)
        end
    end SendMail;

    procedure {public} Synchronise;
    begin
        activity; begin SendMail end; (* Run in a new thread *)
        (* Other synchronisation tasks such as GetMail *)
    end Synchronise;

begin (* object MailClient *)
    smtp := nil; (* initialisation code on instantiation *)
end (* of object *) MailClient.


(* This is the loadable module called User that it the initial root of program execution *)
(* It creates the mail client and server objects and then configures then to communicate with each other *)
module User;
    var server: MailServer; (* declare variables for referencing each object *)
    client: MailClient;

begin (* these statements are run when the module is loaded into memory and initialised *)
    server := new MailServer; (* instantiate the MailServer object *)
    client := new MailClient; (* instantiate the MailClient object *)
    client.Configure( server ); (* call method in client object to link it with the server *)
    client.Synchronise( ); (* call method in client object to initially synchronise the protocol *)
end User .
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.