threadのお勉強(with python)
ROS x thread x pythonのコードを読みながらthreadの理解、実装方法を学ぶ
python並列化
threading.Thread
multiprocessing.Process
Pythonのマルチスレッド処理:threading, multiprocessing | UX MILK
python x threadについて
Pythonのthreading.Threadとmultiprocessing.Process [ pLog ] 👈イイね!
Python の threading.Lock を試してみる | CUBE SUGAR STORAGE
pythonのcopyについて
8.10. copy — 浅いコピーおよび深いコピー操作 — Python 3.5.3 ドキュメント
https://teratail.com/questions/40811
pythonの値渡し、参照渡しについて
Pythonの値渡しと参照渡し - amacbee's blog
copy – オブジェクトのコピー - Python Module of the Week
pythonのselfについて
和訳 なぜPythonのメソッド引数に明示的にselfと書くのか | TRIVIAL TECHNOLOGIES 4 @ats のイクメン日記
ROS x thread x pythonのコード
jsk_robot/OdometryFeedbackWrapper.py at master · jsk-ros-pkg/jsk_robot · GitHub
self.lock = threading.Lock() ~ def source_odom_callback(self, msg): with self.lock: ~
のようにlockを用いてthread safeを実現
def feedback_odom_callback(self, msg): if not self.odom: return self.feedback_odom = msg with self.lock: # check distribution accuracy nearest_odom = copy.deepcopy(self.odom) nearest_dt = (self.feedback_odom.header.stamp - self.odom.header.stamp).to_sec()
lockした状態のself.odomの中身を深いcopyでnearest_odomに格納。
参考:Python の threading.Lock を試してみる | CUBE SUGAR STORAGE
dynamic_reconfigure/server.py at master · ros/dynamic_reconfigure · GitHub
mutex: 排他制御 http://wa3.i-3-i.info/word13360.html
上記と同じ。lockを使用。
ドローン画像取得 (Erle-Copter, ArduPilot) - Qiita
from threading import Thread, Lock VERBOSE=True import copy mutex = Lock() topic_name = "/camera/image/compressed" class web_video_server: def __init__(self): '''Initialize ros publisher, ros subscriber''' # subscribed Topic self.subscriber = rospy.Subscriber(topic_name, CompressedImage, self.callback, queue_size = 1) if VERBOSE : print "subscribed to " + topic_name def getCompressedImage(self): mutex.acquire(1) result = copy.deepcopy(self.np_arr); mutex.release() return result; def callback(self, ros_data): '''Callback function of subscribed topic. ''' mutex.acquire(1) self.np_arr = ros_data.data; mutex.release()
acquireとreleaseを使用。上記の with self.lock: でも良い。
lockした状態のself.np_arrの中身を深いcopyでresultに格納。
画像をgetするとき、callbackで更新するときそれぞれlockしている。
robot_blockly/image_server.py at master · erlerobot/robot_blockly · GitHub
http://files.cnblogs.com/files/cv-pr/ros_by_example_vol2_indigo.pdf
全体参考
Pythonで学ぶ 基礎からのプログラミング入門 (33) マルチスレッド処理を理解しよう(後編) | マイナビニュース