[Stackless] How to "transfer" a tasklet to the current thread

Anselm Kruis a.kruis at science-computing.de
Thu Nov 7 15:41:35 CET 2013


Hi,

I have the following use case: the main thread unpickles a tasklet and 
some assorted data and decides, that the tasklet shall be run on a 
worker thread.

Problem: as far as I know, a tasklet bound to a thread (via cstate) and 
this association can't be changed. The best we can do is to create a new 
tasklet on the worker thread, that belongs to the worker thread.

Correct?

No I can't simply unpickle the tasklet again. Therefore I need to move 
the state from the first tasklet to a newly created one. Currently I 
have the following method:

import stackless
import thread
def to_current_thread(task):
     """
     Get a tasklet for the current thread.

     If the tasklet already belongs to the current thread, this
     method returns the tasklet unmodified.

     Otherwise, this method tries to
     unbind the tasklet and returns a newly created tasklet. If
     unbinding fails, the method raises :exc:`RuntimeError`.
     """
     if task.thread_id == thread.get_ident():
         return task
     reducedTask = task.__reduce__()
     # raise RuntimeError, if task is alive but not paused
     task.bind(None)

     if True:  # python will crash if set to False
         frameList = reducedTask[2][3]
         for i in range(len(frameList)):
             frame = frameList[i]
             if isinstance(frame, stackless.cframe):
                 reducedFrame = frame.__reduce__()
                 newFrame = reducedFrame[0](*reducedFrame[1])
                 newFrame.__setstate__(reducedFrame[2])
                 frameList[i] = newFrame
     # rebind the task
     task = reducedTask[0](*reducedTask[1])
     task.__setstate__(reducedTask[2])
     return task

# extend the tasklet
stackless.tasklet.to_current_thread = to_current_thread


Is this method correct? Anything to improve?

Regards
   Anselm


-- 
  Dipl. Phys. Anselm Kruis                       science + computing ag
  Senior Solution Architect                      Ingolstädter Str. 22
  email A.Kruis at science-computing.de             80807 München, Germany
  phone +49 89 356386 874  fax 737               www.science-computing.de
-- 
Vorstandsvorsitzender/Chairman of the board of management:
Gerd-Lothar Leonhart
Vorstand/Board of Management:
Dr. Bernd Finkbeiner, Michael Heinrichs, 
Dr. Arno Steitz, Dr. Ingrid Zech
Vorsitzender des Aufsichtsrats/
Chairman of the Supervisory Board:
Philippe Miltin
Sitz/Registered Office: Tuebingen
Registergericht/Registration Court: Stuttgart
Registernummer/Commercial Register No.: HRB 382196




More information about the Stackless mailing list