Question

I've made a huge google research about Stackless Python's tasklets. Every source mentions it as a thread

stackless.com : Microthreads: tasklets wrap functions allowing them to be launched as microthreads.

disinterest.orgv: Tasklets — Lightweight threads

But tasklets are not concurent. They execute a part by part of a code.

Code like this:

def function(n):
   print n
   print n
   stackless.schedule()

stackless.tasklet(function)(3)
stackless.tasklet(function)(10)
stackless.run()

Will print

3
3
10
10

A tasklet executes a code until it encounters stackless.schedule() then it executes the next tasklet from beginning or from place of last pause.

Every programmer knows the golden rule of "no GOTO". My questions are:

How is that different from GOTO?
What are advantages of using tasklets if they are not executing parallely?
Why is every source mentioning them as a threads alternative if they're not really threads?

Was it helpful?

Solution

How is it different from goto?

This is different from goto in that you're not specifying where you're going to. By yielding your tasklet (calling stackless.schedule()), all you're saying is "I'm done for now; you can get back to me later" instead of "start executing from line n of file x". The advice "goto is bad" stems from the fact that it allows you to write spaghetti code, where the execution of your program is impossible to follow. Tasklets (or coroutines), on the other hand, are much better in this respect because you know each tasklet will run to completion.

What are advantages of using tasklets if they are not executing parallely?

Concurrency is different from parallelism. Parallelism is when two tasks literally run simultaneously. Concurrency is when two tasks can overlap in their execution, but they may not necessarily both be running at the exact same instant. Tasklets are concurrent but not parallel. The advantage of tasklets is, basically, concurrency.

Why is every source mentioning them as a threads alternative if they're not really threads?

They are a threads alternative if you can give up parallelism, in order to obtain lower overhead. They are still threads in that they still allow multiple concurrent execution paths, even if they are not strictly parallel.

OTHER TIPS

I dont see how this is at all similar to goto imagine the following.

def Eat():
   while True:
        do_something()
        stackless.schedule()
def Play():
   while True:
        do_another_thing()
        stackless.schedule()

def Sleep():
    while True:
        do_something_else()
        stackless.schedule()

stackless.tasklet(Eat)()
stackless.tasklet(Play)()
stackless.tasklet(Sleep)()

it is essentially single core threading where each thread gets to decide when its going to give up control to another waiting task

its very simillar to how a real-time operating system implements task scheduling

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top