gpt4 book ai didi

python - 计算我访问某个线程的次数

转载 作者:行者123 更新时间:2023-12-01 05:40:52 25 4
gpt4 key购买 nike

我有以下代码来计算我访问线程的次数。代码运行良好,但我想知道是否可以在不涉及任何全局变量的情况下实现。

import threading
import lib.logging
import time

count = 0

class Monitor(threading.Thread):
def __init__(self, count):
threading.Thread.__init__(self)

def run(self):
global count
count+=1
lib.logging.debug ("Count is: " + str(count))

def main():
for i in xrange(3):
t1 = Monitor(count)
t2 = Monitor(count)
t1.start()
t2.start()
t1.join()
t2.join()
time.sleep(3)

print "done"

非常感谢

最佳答案

可以使用itertools.count和Python的函数默认参数行为来计算没有全局变量的函数调用:

import threading
import lib.logging
import time
from itertools import count


class Monitor(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)

def run(self, count=count()):
# next(count) starts from 0, so to log first '1', + 1 is used
lib.logging.debug ("Count is: " + str(next(count) + 1))

def main():
for i in xrange(3):
t1 = Monitor()
t2 = Monitor()
t1.start()
t2.start()
t1.join()
t2.join()
time.sleep(3)

print "done"

这是一篇关于 python 函数默认参数的文章:http://www.lexev.org/en/2013/python-mutable-default-arguments/

关于python - 计算我访问某个线程的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com