Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

multithreading - Multi Threading python problem, not printing

I am currently learning multithreading and learned about concurrent.futures and the threading pool executor, i tried to implement an example but for some reason it was not printing the multiple print orders. where did i go wrong?

import requests
import random
import string
import concurrent.futures

result = open(r"workingGhosts.txt","w")
length = 5
url ="https://ghostbin.co/paste/"

def get_random_string(length):
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    return result_str

times = int(input("how many times do you want to check?"))

list_urls=[]

counter = 0
for x in range(times):
    stringA = url + get_random_string(length)
    list_urls.append(stringA)

def lol(finalUrl):
    r = requests.get(finalUrl)
    counter= counter +1
    print("printing")
    if r.status_code != 404:
        result.write(finalUrl)


with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.map(lol,list_urls)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'ts not printing because there is an exception. these aren't shown to you unless you check for them yourself while using an executor
the exception you are getting is:

UnboundLocalError: local variable 'counter' referenced before assignment

because of this line

counter= counter +1

change lol like this:

def lol(finalUrl):
    global counter  # add this line
    r = requests.get(finalUrl)
    counter= counter +1
    print("printing")
    if r.status_code != 404:
        result.write(finalUrl)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...