Fine thread control, Run only n bytecodes
Christopher T King
squirrel at WPI.EDU
Fri Jul 16 16:01:39 EDT 2004
On Fri, 16 Jul 2004, David Pokorny wrote:
> I'd like to be able to take a function or other chunk of code (that someone
> else has written), run it for, say 50 byte codes, and then return control
> back to my program/controlling thread until my program/controlling thread
> indicates that it wants to run the next 50 bytes codes of the foreign
> program, etc...
>
> Is there an extension to the python threading module that supports such fine
> control?
Not that I know of (Python doesn't support per-bytecode hooks), but you
can get a similar effect after every X lines using settrace() and Lock
objects (untested):
count=0
main_lock=Lock()
thread_lock=Lock()
def local_tracer(f,e,a):
global main_lock, thread_lock, count
count-=1
if not count:
main_lock.release()
thread_lock.acquire()
return local_tracer
def global_tracer(f,e,a):
return local_tracer
def mythread():
global thread_lock
sys.settrace(tracer)
thread_lock.acquire()
do_stuff()
def waitfor(n):
global main_lock, thread_lock, count
count=n
thread_lock.release()
main_lock.acquire()
def main():
thread_lock.acquire()
main_lock.acquire()
start_thread(mythread)
while True:
waitfor(50)
do_stuff()
There's probably a more direct way about this, though.
More information about the Python-list
mailing list