我没有为我的查询提到搜索结果,也找不到我的解决方案。 下面的代码用于模拟几乎与我的需求相等的代码。我正在使用spyder IDE,在某些情况下,我将在spyder的Ipython控制台中调用该函数并更改变量..etc。在使用线程处理时,会发现一些性能延迟,以及如何在多处理中实现这一点,因为我还必须在实例和函数之间共享数据。
readonly
使用线程共享内存..以及如何在多处理中使用?
import time
import struct
import queue
import random
from threading import Thread
# Class for Data generation and processing
class datagenerator:
def __init__(self):
self.st = struct.Struct("<lh20s200s100s")
self.notbreakloop = True
self.que = queue.Queue()
self.dict = {}
self.dictcal = {}
def bytesgenerator(self):
while self.notbreakloop:
i = random.randint(10,10000)
bytesstruct = self.st.pack(1,i,"20s".encode("ascii"),"200s".encode("ascii"), "100s".encode("ascii"))
self.que.put(bytesstruct)
time.sleep(5)
def worker(self):
while self.notbreakloop:
try:
bytesmsg = self.que.get()
tup = self.st.unpack(bytesmsg)
self.dict[tup[0]] = tup
time.sleep(4)
except Exception:
pass
def calculator(self,key,a,b,):
self.dictcal[key] = a/b
# User class
class strategy:
def __init__(self, val):
self.val = val
def userrun(self):
while tt.notbreakloop:
try:
#getting value from datagenerated instance
val1 = tt.dict.get(1,())[1]
tt.calculator(key=str(self.val), a=val1, b=self.val)
time.sleep(3)
except IndexError:
pass
except Exception:
pass
tt = datagenerator()
s1 = strategy(5)
s2 = strategy(10)
s3 = strategy(15)
在Ipython控制台中调用dict值,有时我也可以更改变量状态
data = Thread(target=tt.bytesgenerator)
data2 = Thread(target=tt.worker)
user1 = Thread(target=s1.userrun)
user2 = Thread(target=s2.userrun)
user3 = Thread(target=s3.userrun)
data.start()
data2.start()
user1.start()
user2.start()
user3.start()