我如何使它成为多线程的



我制作了一个Python脚本,模拟骰子,然后计算相对频率。

我想,为什么不让它成为多线程的呢?现在我被变量卡住了。如果我运行这个,就像最后一个线程覆盖所有其他结果一样,所以它将运行多线程,但只执行最后一个执行线程的结果。根据您的需要修改变量,将其设置为8,这样您就可以看到只有2个随机数,并在最后计算为百分比。不要修改NrThreads,因为它总是从4开始。

import threading
import random

### CONFIGURE
tries=8
NrThreads=4
triesThread=round(round(tries)/4)
###CONFIGURE
def ThreadCode():
global one
global two
global three
global four
global five
global six
one=0
two=0
three=0
four=0
five=0
six=0
for i in range(0, triesThread):
number=random.randint(1,6)
if (number == 1):
one=one+1
if (number == 2):
two=two+1
if (number == 3):
three=three+1
if (number == 4):
four=four+1
if (number == 5):
five=five+1
if (number == 6):
six=six+1
thread1 = threading.Thread(target=ThreadCode)
thread1.start()
print("Started thread")
thread2 = threading.Thread(target=ThreadCode)
thread2.start()
print("Started thread")
thread3 = threading.Thread(target=ThreadCode)
thread3.start()
print("Started thread")
thread4 = threading.Thread(target=ThreadCode)
thread4.start()
print("Started thread")
thread1.join()
thread2.join()
thread3.join()
thread4.join()
print("Number 1: ", one)
print("Number 2: ", two)
print("Number 3: ", three)
print("Number 4: ", four)
print("Number 5: ", five)
print("Number 6: ", six)
p1=one/tries
print("Probability for number 1: ", p1)
for i in ([one, two, three, four, five, six]):
print(i/tries,"  ", i/tries*100,"%")

您的代码有几个问题:

  1. 您可以在每个线程中将数字重置为0。每次进入函数时,它们都会返回到0
  2. 你的代码不是线程安全的。不能在同一编号的多个线程中使用+=,否则它会相互覆盖

请记住,这段代码实际上不会更快,因为Python有一个全局解释器锁(GIL(,而且您无论如何都需要对所有添加内容进行锁定。

这是固定代码:

import threading
import random

### CONFIGURE
tries=8
NrThreads=4
triesThread=round(tries/4)
###CONFIGURE
lock = threading.Lock()
one=0
two=0
three=0
four=0
five=0
six=0
def ThreadCode():
global one
global two
global three
global four
global five
global six
for i in range(0, triesThread):
number=random.randint(1,6)
with lock:
match number:
case 1:
one += 1
case 2:
two += 1
case 3:
three += 1
case 4:
four += 1
case 5:
five += 1
case 6:
six += 1
thread1 = threading.Thread(target=ThreadCode)
thread1.start()
print("Started thread")
thread2 = threading.Thread(target=ThreadCode)
thread2.start()
print("Started thread")
thread3 = threading.Thread(target=ThreadCode)
thread3.start()
print("Started thread")
thread4 = threading.Thread(target=ThreadCode)
thread4.start()
print("Started thread")
thread1.join()
thread2.join()
thread3.join()
thread4.join()
print("Number 1: ", one)
print("Number 2: ", two)
print("Number 3: ", three)
print("Number 4: ", four)
print("Number 5: ", five)
print("Number 6: ", six)
p1=one/tries
print("Probability for number 1: ", p1)
for i in ([one, two, three, four, five, six]):
print(i/tries,"  ", i/tries*100,"%")

相关内容

  • 没有找到相关文章

最新更新