为了解决两个线程类通过global 变量传递数据的方法在并发情况下全局变量被覆盖的问题,不得已将两个代理类用一个class来包装,试验了许久才得出这个简单粗暴的方法,留存以备将来参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# coding: utf-8 import threading import queue import time class MainClass: # class attribute to be used in subClass queueTest = None queueStopThread = None def __init__(self): MainClass.queueTest = queue.Queue() MainClass.queueStopThread = queue.Queue() def __del__(self): MainClass.queueTest = None MainClass.queueStopThread = None class SubClass1(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while MainClass.queueStopThread.empty(): if not MainClass.queueTest.empty(): print("{} - {}".format(threading.currentThread().ident, MainClass.queueTest.get())) print("SubClass1: queueStopThread: {}".format(MainClass.queueStopThread.get())) class SubClass2(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for i in range(1, 10): MainClass.queueTest.put(i) time.sleep(0.1) MainClass.queueStopThread.put(True) @staticmethod def run_main(): p_subclass1 = MainClass.SubClass1() p_subclass1.daemon = True p_subclass1.start() p_subclass2 = MainClass.SubClass2() p_subclass2.daemon = True p_subclass2.start() p_subclass1.join() del p_subclass1 del p_subclass2 if __name__ == "__main__": tM1 = MainClass() tM2 = MainClass() t1 = threading.Thread(target=tM1.run_main()) t1.daemon = True t2 = threading.Thread(target=tM2.run_main()) t2.daemon = True t1.start() t2.start() main_class_test = MainClass() main_class_test.run_main() |
运行结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
F:\Python\classInClass\venv\Scripts\python.exe F:/Python/classInClass/classInClass.py 14596 - 1 14596 - 2 14596 - 3 14596 - 4 14596 - 5 14596 - 6 14596 - 7 14596 - 8 14596 - 9 SubClass1: queueStopThread: True 11812 - 1 11812 - 2 11812 - 3 11812 - 4 11812 - 5 11812 - 6 11812 - 7 11812 - 8 11812 - 9 SubClass1: queueStopThread: True 11120 - 1 11120 - 2 11120 - 3 11120 - 4 11120 - 5 11120 - 6 11120 - 7 11120 - 8 11120 - 9 SubClass1: queueStopThread: True Process finished with exit code 0 |
简洁实用,好文章!