加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:54:06 所属栏目:Python 来源:网络整理
导读:我必须在Python 2.7中编写一个类,我有一些问题. 我最近来自java背景和学习python 如果我必须在java中做,我会写这些 public class CommandSender extends Thread { private boolean isTimeOut; private boolean running; private ArrayList 我现在做了什么 cl

我必须在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读