What I want to do is something like this:
class MyThread(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
# self._sock = self.initsocket(host, port)
self._id = random.randint(0, 100)
def run(self):
for i in range(3):
print("current id: {}".format(self._id))
def main():
ts = []
for i in range(5):
t = MyThread("localhost", 3001)
t.start()
ts.append(t)
for t in ts:
t.join()
I got these output:
current id: 10
current id: 10
current id: 13
current id: 43
current id: 13
current id: 10
current id: 83
current id: 83
current id: 83
current id: 13
current id: 98
current id: 43
current id: 98
current id: 43
current id: 98
This output is what I want. As you can see, my _id
is different in different threads, but in single thread, I share the same _id
.(_id
is just one of these variables, I have many other similar variable).
Now, I want to do the same thing with multiprocessing.pool.ThreadPool
class MyProcessor():
def __init__(self, host, port):
# self._sock = self.initsocket(host, port)
self._id = random.randint(0, 100)
def __call__(self, i):
print("current id: {}".format(self._id))
return self._id * i
def main():
with ThreadPool(5) as p:
p.map(MyProcessor("localhost", 3001), range(15))
But now _id
will be share by all threads:
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
current id: 58
And with concurrent.futures.ThreadPoolExecutor
, I also try to do the same thing:
class MyProcessor():
def __init__(self, host, port):
# self.initsocket(host, port)
self._id = random.randint(0, 100)
def __call__(self, i):
print("current id: {}".format(self._id))
return self._id * i
def main():
with ThreadPoolExecutor(max_workers=5) as executor:
func = MyProcessor("localhost", 3001)
futures = [executor.submit(func, i) for i in range(15)]
for f in as_completed(futures):
pass
Output is this:
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
current id: 94
Of course, I get this result is not strange, because I just call __init__
one time. But what I am asking is that:
How can I do the same thing with concurrent.futures.ThreadPoolExecutor
and multiprocessing.pool.ThreadPool
(and also please with no more global variable).