如何在python3中管理函数作用域和同步

2024-09-27 07:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个2个问题变成了1-接下来我从脚本中得到以下输出

Checker: start of thread
Checker: ( 0 ) Hello, world
Checker: ( 1 ) Hello, world
Checker: ( 2 ) How do you do
Checker: ( 3 ) How do you do
Checker: start of thread
Checker: ( 4 ) Bye for now
Checker: exiting thread
Checker: ( 0 ) Bye for now
Checker: exiting thread

剧本:

#!/usr/local/bin/python                                                                                                                           

import time
import threading

class CheckTscope:

def __init__ (self):
    self.name = 'checker'
    self.msg = None

def checker (self, msg="Hey stranger"):
    count = 0
    self.setMessage(msg)
    print ("Checker: start of thread")
    while True:
        time.sleep (0.04)
        print ("Checker: (", count, ")", self.getMessage())
        if self.carry_on:
            count += 1
            continue
        break
    print ("Checker: exiting thread")

def getMessage (self):
    return self.msg

def setMessage (self, text):
    self.msg = text

def construct (self, initxt):
    self.setMessage (initxt)
    self.carry_on = True
    reporter = threading.Thread(target=self.checker, args=(initxt,))
    reporter.start()

def destruct (self):
    self.carry_on = False


if __name__ == '__main__':
    ct = CheckTscope()
    ct.construct("Hello, world")
    time.sleep(0.125)
    ct.setMessage("How do you do")
    time.sleep(0.06)
    ct.destruct()
    time.sleep(0.02)
    ct.checker ("Bye for now")

问题是:

  1. 如何使该类中的其他函数只能访问函数checker()(限制作用域)

  2. 如何为多个线程进行同步(“4-Bye for now”是一个错误,当消息设置为新值时,计数器应该重置)

从本质上说,我在寻找另一种语言中“synchronized private void”的替代品。谢谢你的帮助


Tags: selffortimedefcheckermsgsleepdo
1条回答
网友
1楼 · 发布于 2024-09-27 07:33:31

你不知道。方法和变量的作用域大部分时间是由编程约定处理的。在这种情况下,您可以在checker的begging中添加下划线,以将其标识为只能由类中的其他方法调用的私有方法。 2-要同步多个线程,您需要使用特定于线程的命令来处理线程,尝试像您这样使用“carry\u on”会让您陷入一些奇怪的困境。 Ps:如果我记得有@Async和@Sync注释,您可以进一步研究它

相关问题 更多 >

    热门问题