简体   繁体   中英

how can I get the return value from thread.run

i'm trying to "save" a return value from a function (that returns integer) but i'm getting None object

import threading


class SitesThread(threading.Thread):
    def __init__(self, func, searchLine):
        threading.Thread.__init__(self)
        self.func = func
        self.searchLine = searchLine

    def run(self):
        self.func(self.searchLine)


def print1(searchLine):
    print(searchLine, "this is print 1")
    return 1


def print2(searchLine):
    print(searchLine, "this is print 2")
    return 2


def main():
    threads = []
    line = input("pleAS insert a search line")
    t1 = SitesThread(print1, line)
    t2 = SitesThread(print2, line)
    res1 = t1.start()
    res2 = t2.start()
    threads.append(t1)
    threads.append(t2)
    for t in threads:
        t.join()
    print("thread 1 is alive?", t1.isAlive())
    print(res1)
    print("thread 2 is alive?", t2.isAlive())
    print(res2)


if __name__ == "__main__":
    main()

i'm expecting to get: 'searchLine' this is print 1 'searchLine' this is print 2 thread 1 is alive? False 1 thread 2 is alive? False 2

but i get: i'm expecting to get: 'searchLine' this is print 1 'searchLine' this is print 2 thread 1 is alive? False None thread 2 is alive? False None

I'm unsure how you will get it to return and be placed in the res1 or 2 variable. However you can still print out searchLine portion of your thread. Take a look at the code below

print("thread 1 is alive?", t1.isAlive())
print(t1.searchLine)
print("thread 2 is alive?", t2.isAlive())
print(t2.searchLine)

This will print what you are searching for... so if you searched for 12 it would print 12.

Hope this helps. I'll keep poking around with it and see if I can get something that matches your expected output exactly.

it's seems so far that i can't get a return value from a thread that running a function that returns a value. So if someone have the same problem as I got, one optional solution is to change the function, instead of returning a value it can put the value in a global list (make sure you know exactly where in the list you are saving this value so your other threads won't run it over).

other solution is to use processes instead of threads, but since i'm trying to save time and my functions are all about API requests, iv'e learned that threads are faster than processes in this case.

Hope it will be useful for someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM