[Tutor] threading tutorial

Alan Gauld alan.gauld at yahoo.co.uk
Thu Jun 1 21:17:05 EDT 2017


On 01/06/17 16:30, Michael C wrote:
> Oh i get it alright, however in my code I have to push the W button like
> this:
> 
> import pyautogui
> import time
> 
> pyautogui.keyDown('w')
> time.sleep(2)
> pyautogui.keyUp('w')

So this emulates a user pressing the w key for 2 seconds.
What's not clear is where this appears in your design,
is it part of the code running in the thread or is it
part of the code that stops the thread?

If you can explain a little bit more of the high level
requirement hee rather than the implementation perhaps
we can come up with a better solution - ideally one
that doesn't involve any keypress emulation at all...

> while the example you gave:
> 
>  def fn():
>    global run_me
>    while run_me:
>      ... do some work ...
> 
> and then elsewhere you go:
> 
>  global run_me
>  run_me = True
>  ... create and start the Thread ...
>  ... later ...
>  run_me = False
>  T.join()
> 
> theoretically deals with my problem, in practice though, my function spend
> almost all its time holding down the 'w' button, 

The fact you say the function suggests you mean the thread.
So the question is why does it need to hold the key down
for so long? Indeed why does a background process need
to emulate a button press? What is the button press doing?
Is it in turn detected by some other process/thread? We
need to understand how the various bits interact to give
a better solution.

> Is there a way to pause/kill the thread?

Not really other than setting a flag, but if its the
thread that's doing the sleeping then killing it
won't help - in fact if you could kill it in the
middle of the sleep() you'd have the problem of
a key being "held down" forever - probably a
bad thing... Thats why its better to have the
thread kill itself on detection of the semaphore.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list