LoginSignup
5
1

More than 5 years have passed since last update.

Androidプログラムに慣れた人がPythonでマルチスレッド処理してみる

Posted at

Python初心者で、普段 Android で Java プログラミングしている皆さんは、「スレッド立てるかー、だったら、Handler でメッセージをハンドルするようにしないと」、と思ったりしますよね。ですが、Pythonに対応したものは無いので、一瞬悩みました。
そんなPython初心者のメモ(小ネタ)です。

参考:
http://qiita.com/konnyakmannan/items/2f0e3f00137db10f56a7
http://qiita.com/tortuepin/items/69fa0a307ebf15348885

以下、最初、Python2.7 で開発していたのもので、Python2.7風味です。(できるだけ、sixを使うようにしています)

なんとなく、対応表です。(単なる感覚で書いた表で、深い意味はありません。)

Android Python 備考
Looper なし(while loopで)
Handler Queue Python3 では、queue。six.moves.queueでもok
notify threading.Event AndroidというかJavaですね

Queue

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() # 直前にgetしたタスクが完了したことを通知。join を使わない場合無くて良い
    time.sleep(0.1)

q = queue.Queue()
thread.start_new_thread(target, (q,))

while True:
  q.put("task")
  # q.join() # join を使うと、キューで、全てのアイテムに対して、task_done() されるのを待つ

という感じです.

theading.Event

単に待ちたいだけならば、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"
5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1