计算我访问线程的次数

时间:2013-07-10 15:16:59

标签: python

我有以下代码,它计算我访问线程的次数。代码工作正常,但我想知道是否可以在不涉及任何全局变量的情况下实现。

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"

非常感谢

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是在内存计数器中使用“半持久”。

例如

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import threading
import time
import redis


class RedisCounter(object):

    def __init__(self, db, host, port, key, reset=False):
        pool = redis.ConnectionPool(host=host, port=port, db=db)
        self.conn = redis.StrictRedis(connection_pool=pool)
        self.key = key

        if reset:
            self.initialize()

    def initialize(self):
        self.conn.set(self.key, 0)

    def incr(self):
        self.conn.incr(self.key)

    def get(self):
        return int(self.conn.get(self.key))


class Monitor(threading.Thread):

    def __init__(self, counter):
        threading.Thread.__init__(self)
        self.counter = counter

    def run(self):
        self.counter.incr()
        print("Count is: " + str(self.counter.get()))


def main():
    counter = RedisCounter(0, 'localhost', 6379, 'thread_counter', True)

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

    print "done"

if __name__ == '__main__':
    main()

这对你来说可能是一种矫枉过正,但仍然是解决这个问题的方向:)

答案 1 :(得分:1)

可以使用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/

相关问题