Re: Alternative to signals in threads

2017-03-08 Thread woooee
Use multiprocessing since you want to do multiple things at once 
https://pymotw.com/2/multiprocessing/basics.html  If I understand you 
correctly, once the string is found you would terminate the process, so you 
would have to signal the calling portion of the code using a Manager dictionary 
or list..  I am not that knowledgeable about multiprocessing, so this is 
probably the long way around the barn.
import time
from multiprocessing import Process, Manager


def test_f(test_d):
   ctr=0
   while True:
  ctr += 1
  print "test_f", test_d["QUIT"], ctr
  time.sleep(1.0)
  if ctr > 5:
 test_d["QUIT"]=True
  
if __name__ == '__main__':
   ## define the dictionary to be used to communicate
   manager = Manager()
   test_d = manager.dict()
   test_d["QUIT"] = False

   ## start the process
   p = Process(target=test_f, args=(test_d,))
   p.start()
   
   ## check the dictionary every half-second
   while not test_d["QUIT"]:
  time.sleep(0.5)
   p.terminate()
-- 
https://mail.python.org/mailman/listinfo/python-list


Alternative to signals in threads

2017-03-08 Thread saatomic
I've been unsuccessfully looking for an alternative for signals, that works in 
threads.

After updating a script of mine from being single-threaded to being 
multi-threaded, I realised that signals do not work in threads.

I've used signals to handle blocking operations that possibly take forever like:


signal.signal(signal.SIGALRM, wait_timeout)
# wait_timeout simply does: raise Exception("timeout")
signal.setitimer(signal.ITIMER_REAL,5)
# So a timer of 5 seconds start and I run my operation
try:
       p = Popen(["tool", "--param"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
       for line in p.stdout:
           if "STRING" in str(line):
                     signal.setitimer(signal.ITIMER_REAL,0)
                     p.terminate()
                     print("Success")
except:
       p.terminate()
       print("Timeout")


Now this works great with a single thread, but doesn't work at all with 
multiple threads.
A more throughout example can be found here: 
https://gist.github.com/saatomic/841ddf9c5142a7c75b03daececa8eb17 

What can I use instead of signals in this case?

Thanks and kind regards,
SaAtomic
-- 
https://mail.python.org/mailman/listinfo/python-list