0

好吧,伙计们,我对python有点陌生,我想制作一个简单的多线程脚本,但它没有按计划进行。那么这个脚本做了什么来获取电话号码列表并将您输入的号码附加到其中并打印它,但是当您选择线程数时让我们说3,而不是对列表中的两个号码执行该功能,它对每个数字执行两次该功能。谁能帮我解决这个问题?

from threading import Thread


def test(list):
  i = input('Enter a number: ')
  i = phone[k],i
  print( i , phone[k])

list = ['+4469545444','+15546343565','+145346465343']
threds = int(input('Enter number of threads : '))
phone = []
with open(list) as ph:
for line in list:
   if len(line) > 3:
      phone.append(line.strip())
                
i=0
while True:
   Threads = []
   for k in range(i,i+threds):
    try:
       i+=1
       if(k >= len(phone)):
         break
       th = Thread(target=test,args=[phone[k]])
       th.daemon = True
       th.start()
       Threads.append(th)
    except Exception as e:
       break
   for th  in Threads:
      th.join()
      if(i >= len(phone)):
        break```









4

2 回答 2

0

由于我无法让您的代码运行,即使在您修复它之后,我也自己实现了一个版本:

from threading import Thread

def phone_append(appendex, numbers):
    for number in numbers:
        print(number+appendex)
    

phone = ['+4469545444','+15546343565','+145346465343','+4469545444','+15546343565','+145346465343','+4469545444','+15546343565','+145346465343','+4469545444','+15546343565','+145346465343']

while True:
    try:
        thread_num = int(input("How many threads?"))
        break
    except Exception:
        print("Not a valid number!")
        
appendex = input("What to append?")

for i in range(thread_num):
    thread = Thread(target=phone_append,args=[appendex, phone[::thread_num]])
    thread.start()

请仔细阅读stackoverflow.com/help/minimal-reproducible-example。尝试运行,您发布的内容。请确保,我们实际上可以重现您的问题。

于 2021-01-01T15:02:10.413 回答
0

您在创建线程时传递了当前电话号码,但您不使用它。更改目标函数以使用传递的电话号码。

import threading

def test(ph_no):
    i = input('Enter a number: ')
    print( f'thread:{threading.current_thread().getName()}, original:{ph_no}, adding:{i},  {ph_no}{i}')
于 2021-01-01T15:11:05.380 回答