python - Scoping rules and threads -


this program works (i able hear text speech in action):

import pyttsx import threading  def saythread(location, text):      engine = pyttsx.init()       engine.say(text)     engine.runandwait()   e = (1, "please work, oh god") t = threading.thread(target=saythread,args=e,name='sayitthread') t.start() 

if program changed

import pyttsx import threading def saythread(location, text):      global engine                #(changed) added global       engine.say(text)     engine.runandwait()          e = (1, "please work, oh god")  engine = pyttsx.init()                 #(changed) added variable  t = threading.thread(target=saythread,args=e,name='sayitthread') t.start() 

then gets 'stuck' @ line "engine.runandwait()" , text speech doesn't work. guessing problem lies rules of scoping threads. right? want a.. 'handle' engine variable in main thread. can call engine.stop() main thread.

hope made sense

thanks

global variables bad approach. can pass engine argument saythread:

def saythread(engine, location, text):     engine.say(text)     engine.runandwait()          # ...later...  engine = pyttsx.init()                 #(changed) added variable  t = threading.thread(target=saythread,args=(engine, 1, "here go"),name='sayitthread') t.start() 

but i'd willing bet real problem methods on engine object aren't designed called other threads. (scoping has nothing it, way, depends on design of underlying library.)

it might can around problem using lock:

def saythread(engine, lock, location, text):     lock:         engine.say(text)         engine.runandwait()    engine = pyttsx.init() lock = threading.lock() t = threading.thread(         target=saythread,         args=(engine, lock, 1, "here go"),         name='sayitthread') t.start() 

...but if doing else engine object concurrently didn't like. code, doesn't it's case, might have live creating each engine object within thread, , finding way pass around state. alternatively, can keep engine in main thread, , use queue call from other threads you're doing other work.

it's worth remembering not python libraries (especially written in c) support threads @ all, have careful, read documentation or ask author.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -