How to make this script “thread-safe”?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import os, sys, time from threading import Thread from threading import currentThread import SimpleXMLRPCServer servAddr = ("localhost", 8000) serv = SimpleXMLRPCServer.SimpleXMLRPCServer(servAddr) tt = [] import SimpleXMLRPCServer class myThread(Thread): def __init__ (self,p): self.p = p Thread.__init__(self) def run (self): t = currentThread() while 1: n = random.random() tt[self.p] = self.p + '!!!' time.sleep(n) def rn(): mythreads = [] for p in (1,2,3): t = myThread(p) mythreads.append(t) t.start() return 1 def test(): return tt serv.register_function(rn) serv.register_function(test) serv.register_introspection_functions() |
像dict这样的python对象已经是线程安全的,所以从这个意义上说,您的脚本已经是线程安全的。你还想让线程安全,至少现在看起来还可以
我对python不太熟悉,但是您不能使用信号量/监视器进行原子保险吗?