0

我无法使用线程在 python 中编写基准代码。我能够让我的线程工作,但我不能让我的对象返回一个值。我想获取这些值并将它们添加到列表中,以便计算翻牌。

创建类以执行线程

class myThread(threading.Thread):

    def calculation(self):
        n=0
        start=time.time()
        ex_time=0
        while ex_time < 30:
            n+=1
            end=time.time()
            ex_time=end-start
        return ex_time 


    def run(self): 
        t = threading.Thread(target = self.calculation)
        t.start()

创建线程的函数

def make_threads(num):
    times=[]
    calcs=[]
    for i in range(num):
        print('start thread', i+1)
        thread1=myThread()
        t=thread1.start()
        times.append(t)
     #calcs.append(n)
    #when trying to get a return value it comes back as none as seen
    print(times)
#average out the times,add all the calculations to get the final numbers
#to calculate flops
    time.sleep(32) #stop the menu from printing until calc finish


def main():

    answer=1
    while answer != 0:
        answer=int(input("Please indicate how many threads to use: (Enter     0 to exit)"))
        print("\n\nBenchmark test with ", answer, "threads")
        make_threads(answer)

main()
4

1 回答 1

0

有两种方法可以做到这一点:

1. 使用静态变量(hacky,但高效快捷)

定义一些全局变量,然后在线程中进行操作。IE:

import threading
import time

class myThread(threading.Thread):

    def calculation(self):
        n=0
        start=time.time()
        ex_time=0
        print("Running....")
        while ex_time < 30:
            n+=1
            end=time.time()
            ex_time=end-start

        self.myThreadValues[self.idValue] = ex_time
        print(self.myThreadValues)
        return ex_time 

    def setup(self,myThreadValues=None,idValue=None):
        self.myThreadValues = myThreadValues
        self.idValue = idValue


    def run(self): 
        self.calculation()
        #t = threading.Thread(target = self.calculation)
        #t.start()

def make_threads(num):
    threads=[]
    calcs=[]
    myThreadValues = {}

    for i in range(num):
        print('start thread', i+1)
        myThreadValues[i] = 0
        thread1=myThread()
        thread1.setup(myThreadValues,i)
        thread1.start()
        #times.append(t)
        threads.append(thread1)

    # Now we need to wait for all the threads to finish. There are a couple ways to do this, but the best is joining.

    print("joining all threads...")
    for thread in threads:
        thread.join()

    #calcs.append(n)
    #when trying to get a return value it comes back as none as seen

    print("Final thread values: " + str(myThreadValues))
    print("Done")
    #average out the times,add all the calculations to get the final numbers
    #to calculate flops
    #time.sleep(32) #stop the menu from printing until calc finish

def main():

    answer=1
    while answer != 0:
        answer=int(input("Please indicate how many threads to use: (Enter     0 to exit)"))
        print("\n\nBenchmark test with ", answer, "threads")
        make_threads(answer)

main()

2. 正确的方法是使用流程

进程设计用于来回传递信息,而不是通常用于异步工作的线程。请参阅此处的说明:https ://docs.python.org/3/library/multiprocessing.html

请参阅此答案:如何恢复传递给 multiprocessing.Process 的函数的返回值?

import multiprocessing
from os import getpid

def worker(procnum):
    print 'I am number %d in process %d' % (procnum, getpid())
    return getpid()

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print pool.map(worker, range(5))
于 2018-11-27T03:46:20.507 回答