Views
samples
last edited 3 years ago by sholloway
You can copy the following sample code snippets directly into a Python interpreter session or run them as scripts.
Tasklets and channels
The following does only create a tasklet from a callable, in this case a function. The tasklet also gets bound to arguments for the callable. Then it is run.
Example: Creating a tasklet from a callable:
from stackless import tasklet
def func():
print 42
t = tasklet(func) # bind tasklet to a callable
t = t() # bind tasklet to callable's arguments
t.run()
# should print: 42
Example: Creating a channel:
import stackless ch = stackless.channel()
Simple communication
Sample 1
The following sample creates a channel with one sending and one receiving tasklet on it. The sending tasklet sends the value 42 which is received and printed by the other tasklet.
Example: Simple channel send between two explicit tasklets:
import stackless
def recv(chan):
print chan.receive()
def send(chan, val):
chan.send(val)
ch = stackless.channel()
t_recv = stackless.tasklet(recv)(ch)
t_send = stackless.tasklet(send)(ch, 42)
stackless.run()
# should print: 42
Pickling
Example: Pickling and unpickling simple tasklets:
from stackless import run, schedule, tasklet
import pickle
def aCallable(name):
print " aCallable<%s>: Before schedule()" % (name,)
schedule()
print " aCallable<%s>: After schedule()" % (name,)
tasks = []
for name in "ABCDE":
tasks.append(tasklet(aCallable)(name))
print "Schedule 1:"
schedule()
print
print "Pickling..."
pickledTasks = pickle.dumps(tasks)
print
print "Schedule 2:"
schedule()
unpickledTasks = pickle.loads(pickledTasks)
for task in unpickledTasks:
task.insert()
print
print "Schedule Unpickled Tasks:"
schedule()
Scheduling
foo
Stackless Python