Python的等效Java函数wait(),notify(),synchronized

我必须在Python 2.7中编写一个类,我有一些问题.
我最近来自java背景和学习python

如果我必须在java中做,我会写这些

public class CommandSender extends Thread {
    private boolean isTimeOut;
    private boolean running;
    private ArrayList

我现在做了什么

class CommandSender(threading.Thread)

     def __init__(self):
         threading.Thread.__init__(self)
         self.waiting_list = []
         self.running = False
         self.is-time_out = False
         self.my_lock = threading.Lock()

     def run(self):
         self.running = True
         with self.my_lock:
             while len(self.waiting_list) == 0 and self.running:
                 # Don't know what I have to do here
             while len(self.waiting_list) != 0 and self.running:
                 # Do my stuff

     def send_command(self,cmd):
         with self.my_lock:
             self.waiting_list.append(cmd)
             # Notify ?

     def is_time_out(self):
         with self.my_lock:
             return self.is_rime_out

我为每个实例使用一个锁,因为只有一个CommandSender实例

那么如何进行等待/通知过程?我的同步块是否很好用?

谢谢 !

最佳答案
首先,您应该知道Python的global interpreter lock不允许多个线程同时运行Python代码(尽管线程可以运行,例如C代码,例如使用本机代码模块,如果它们适当地释放GIL).如果您需要使用Python代码来使用多核CPU,请查看multiprocessing模块.

现在,直接等效于threading.Event类.创建一个Event对象,然后使用wait和set.

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...