今天 W3Cschool 小編將為大家?guī)淼氖荘ython如何使用多線程的方法來重新排列數(shù)組,希望能對各位有所幫助。
假設有字符數(shù)組就像'XOOOXOX',我需要重新安排這個數(shù)組一樣'XXXOOOO'。那么如何創(chuàng)建簡單的python代碼,使用多線程的方法來重新排列數(shù)組呢?
我就創(chuàng)建了一個虛擬的線程工作,這可能根本不會顯示性能提高:
import random
import threading
a = random.choices(['X', 'O'], k=10000)
a = ''.join(a)
print(a.count('X'), a.count('O'))
thread_count = 4
lock = threading.Lock()
x_count = 0
o_count = 0
def chunk_it(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
def d(i):
global x_count
global o_count
data_part = chunk_it(a, thread_count)[i]
with lock:
x_count += data_part.count('X')
o_count += data_part.count('O')
ts = []
for i in range(thread_count):
t = threading.Thread(target=d, args=(i, ))
ts.append(t)
for t in ts:
t.start()
for t in ts:
t.join()
a = 'X' * x_count + 'O' * o_count
print(a)
print(a.count('X'), a.count('O'))
此演示旨在使用 Python 相對較低的線程 api 顯示。蛇的并發(fā)性由幾個模塊領導threading
, multiprocessing
, concurrent.futures
, asyncio
等等。
Python如何使用多線程的方法來重新排列數(shù)組,就為大家介紹到這里了希望大家繼續(xù)關注W3Cschool.