If you're new to Python and usually program Java on Android, you might think, "Would you like to set up a thread, then you have to handle the message with Handler?" However, there is no Python compatible version, so I was worried for a moment. This is a memo (small story) for Python beginners.
reference: http://qiita.com/konnyakmannan/items/2f0e3f00137db10f56a7 http://qiita.com/tortuepin/items/69fa0a307ebf15348885
The following is the one that was originally developed with Python2.7 and has a Python2.7 flavor. (I try to use six as much as possible)
Somehow, it is a correspondence table. (It's just a table written with a sense, and it doesn't have a deep meaning.)
Android | Python | Remarks |
---|---|---|
Looper | None(with a while loop) | |
Handler | Queue | In Python3, queue. six.moves.Even queue is ok |
notify | threading.Event | Android or Java |
http://docs.python.jp/2/library/queue.html
import six.moves.queue as queue
import six.moves._thread as thread
import time
def target(q):
while True:
print "loop"
print q.get()
# q.task_done() #Notifies that the task obtained immediately before is completed. Not required if you don't use join
time.sleep(0.1)
q = queue.Queue()
thread.start_new_thread(target, (q,))
while True:
q.put("task")
# q.join() #With join, in the queue, for all items, task_done()Wait to be done
It's like that.
If you just want to wait, use theading.Event.
import threading
import six.moves._thread as thread
import six
import time
def target(event):
for cnt in six.moves.range(0, 10):
print "loop:", cnt
time.sleep(0.1)
event.set()
event = threading.Event()
thread.start_new_thread(target, (event,))
event.wait()
print "done"
Recommended Posts