1

I have the following code which is counting how many times I visit a thread. The code is working fine, but I want to find out if that is possible to implement without any global variable involved.

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"

Thanks a lot

4

2 回答 2

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()

这对您来说可能有点过头了,但仍然是解决此类问题的方向:)

于 2013-07-10T15:29:21.657 回答
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/

于 2013-07-10T15:32:09.027 回答