有没有办法在python中跨线程添加变量

时间:2014-07-12 21:21:31

标签: python multithreading variables python-2.7

有没有办法让我可以在活动线程中拥有一个变量,如下面的

count = 0
threadA(count)
threadB(count)

threadA(count):
    #do stuff
    count += 1
threadB(count):
    #do stuff
    print count

这样计数会打印1吗?我更改了线程A中的变量,它反映到另一个线程?

2 个答案:

答案 0 :(得分:1)

您的变量count已经可用于所有线程。但是您需要同步对它的访问,否则您将失去更新。考虑使用锁来保护对计数的访问。

答案 1 :(得分:0)

如果要使用进程而不是线程,请使用multiprocessing。它具有更多功能,包括具有Manager个对象,可以为您处理共享对象。作为一个特权,你可以跨机器共享对象!

import multiprocessing, signal, time

def producer(objlist):
    '''
    add an item to list every sec
    '''
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            return
        msg = 'ding: {:04d}'.format(int(time.time()) % 10000)
        objlist.append( msg )
        print msg


def scanner(objlist):
    '''
    every now and then, consume objlist & run calculation
    '''
    while True:
        try:
            time.sleep(3)
        except KeyboardInterrupt:
            return
        print 'items: {}'.format( list(objlist) )
        objlist[:] = []


def main():

    # create obj sharable between all processes
    manager = multiprocessing.Manager()
    my_objlist = manager.list() # pylint: disable=E1101

    multiprocessing.Process(
        target=producer, args=(my_objlist,),
    ).start()

    multiprocessing.Process(
        target=scanner, args=(my_objlist,),
    ).start()

    # kill everything after a few seconds
    signal.signal(
        signal.SIGALRM, 
        lambda _sig,_frame: manager.shutdown(),
        )
    signal.alarm(12)

    try:
        manager.join() # wait until both workers die
    except KeyboardInterrupt:
        pass


if __name__=='__main__':
    main()