Escolar Documentos
Profissional Documentos
Cultura Documentos
&
COROUTINES
Presented by
Jaisha P. M.
CJB0909001, PEMP FT-’09
M. Sc. (Engg.) in Computer Science and Networking
Module Leader
Prof. N. D. Gangadhar
• Iterator has:
– Sequence S
– A current position in S
– A way of stepping to the next position in S,
and making it the current position
ListIterator
• First()
• Next()
• IsDone()
• Current Item
• // C++ code
ListIterator<Employee> itr = list.iterator();
for(itr.First(); !itr.IsDone(); itr.Next()) {
cout << itr.CurrentItem().toString();
String ID = "Two";
Iterator<BankAccount> i = bank.iterator();
while(i.hasNext()) {
if(i.next().getID().equals(searchAcct.getID()))
System.out.println("Found " + ref.getID());
}
M.S.Ramaiah School of Advanced Studies 7
ITERATORS
Iteration Protocol
• Iteration Protocol instead of Iteration
Classes
• The protocol returns 2 objects, 3functions:
Iteration-protocol(object)=>state, limit,
next, done?, current.
• Designed for optimization
•The call brings the control to the statement where the caller was
suspended. Routines organized in this way are called coroutines.
M.S.Ramaiah School of Advanced Studies 12
COROUTINES
/* -------------------------------------------------------- */
* ------------------------------------------------------ */ /* Function Prototypes */
/* PROGRAM pingpong : */ /* --------------------------------------------------------- */
/* This program uses setjmp() and longjmp() to void Ping(void);
implement an example of coroutine. */ void Pong(void);
/* ----------------------------------------------------- */ /* ---------------------------------------------------- */
/* The main program starts here */
#include <stdio.h> /* -------------------------------------------- --------- */
#include <setjmp.h> void main(int argc, char* argv[])
{
int max_iteration; /* the max # of iterations*/ if (argc != 2) {/* check # of arguments */
int iter; /* global iteration counter */ printf("Use %s max-#-of-lines\n", argv[0]);
exit(1); }
jmp_buf Main; /* jump back to main() */ max_iteration = abs(atoi(argv[1]));
jmp_buf PointPing; /* jump buffer in Ping() */ /* get max # of iterations */
jmp_buf PointPong; /* jump buffer in Pong() */ iter = 1; /* initial iteration count*/
if (setjmp(Main) == 0) / * set a return mark*/
Ping(); /* initialize Ping() */
if (setjmp(Main) == 0) /* set a return mark */
Pong(); /* initialize Pong() */
longjmp(PointPing, 1); /* ok, jump to Ping() */
}
References
[1].Donald. E. Knuth, The Art of Computer Programming-Vol 1-
Fundamental Algorithms, 3rd Edition, 1997.
[2].James W. Cooper, Java Design Patterns: A Tutorial, Pearson
Education Asia, 3rd Edition, 2002.
[3].Goodrich and Tomassia, Data Structures and Algorithms in Java,
2nd Edition.
[4].http://www.csl.mtu.edu/cs4411.ck/www/NOTES/non-local-
goto/coroutine.html.
[5].http://www.softpanorama.org/Lang/Cilorama/coroutines_in_c.sht
ml
[6].http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
M.S.Ramaiah School of Advanced Studies 17