如何使这个脚本“线程安全”?
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像 dict 这样的 Python 对象已经是线程安全的,因此从这个意义上说,你的脚本已经是线程安全的。您还想让线程安全的其他具体事情是什么,至少现在看起来还不错
Python objects like dict are already thread safe, so in that sense your script is already thread safe. What other specific thing you want to make thread safe, at-least for now it looks ok
我对 python 不太熟悉,但是你不能使用信号量/监视器来实现原子保险吗?
I am not really familiar with python, but can't you use Semaphores / Monitors for atomic insurance?