Home

Tags

Как использовать локальную память потока

2010-10-08 python threading потоки

Для этого нужно создать один экземпляр класса threading.local() и использовать его во всех потоках.

Пример

# coding:utf8

import thread
import threading
import time
from random import randint

storage = threading.local()

def foo():
    print storage.A

def myThread():
    storage.A = randint(0,100)
    for x in xrange(10):
        foo()
        time.sleep(0.4)

thread.start_new_thread(myThread, tuple([]))
thread.start_new_thread(myThread, tuple([]))
thread.start_new_thread(myThread, tuple([]))
time.sleep(5)

Результат

100
50
27
100
50
27
...
Каждый поток имеет свое значение storage.A