【问题标题】:Creating Threads in python在 python 中创建线程
【发布时间】:2011-02-23 18:13:49
【问题描述】:

我有一个脚本,我希望一个函数与另一个函数同时运行。

我看过的示例代码:

import threading

def MyThread (threading.thread):
    # doing something........

def MyThread2 (threading.thread):
    # doing something........

MyThread().start()
MyThread2().start()

我无法正常工作。我更愿意使用线程函数而不是类来实现这一点。

这是工作脚本:

from threading import Thread

class myClass():

    def help(self):
        os.system('./ssh.py')

    def nope(self):
        a = [1,2,3,4,5,6,67,78]
        for i in a:
            print i
            sleep(1)


if __name__ == "__main__":
    Yep = myClass()
    thread = Thread(target = Yep.help)
    thread2 = Thread(target = Yep.nope)
    thread.start()
    thread2.start()
    thread.join()
    print 'Finished'

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    您不需要使用 Thread 的子类来完成这项工作 - 看看我在下面发布的简单示例,看看如何:

    from threading import Thread
    from time import sleep
    
    def threaded_function(arg):
        for i in range(arg):
            print("running")
            sleep(1)
    
    
    if __name__ == "__main__":
        thread = Thread(target = threaded_function, args = (10, ))
        thread.start()
        thread.join()
        print("thread finished...exiting")
    

    这里我展示了如何使用线程模块来创建一个调用普通函数作为其目标的线程。你可以看到我如何在线程构造函数中传递我需要的任何参数。

    【讨论】:

    • 我试过这个。我在上面添加了脚本。你能告诉我如何让第二个函数与第一个函数一起运行吗?谢谢
    • @chrissygormley: join() 阻塞直到第一个线程完成。
    • @chrissygormley:如前所述,加入阻塞直到你加入的线程完成,所以在你的情况下,以你的第二个函数作为目标启动第二个线程,以并行运行这两个函数,然后如果您只想等到它们完成,则可以选择加入其中之一。
    • 我一直把exiting读成exciting,反正我觉得这样更合适。
    【解决方案2】:

    您的代码存在一些问题:

    def MyThread ( threading.thread ):
    
    • 您不能使用函数进行子类化;只用一个类
    • 如果您要使用子类,则需要 threading.Thread,而不是 threading.thread

    如果你真的想只使用函数,你有两个选择:

    带线程:

    import threading
    def MyThread1():
        pass
    def MyThread2():
        pass
    
    t1 = threading.Thread(target=MyThread1, args=[])
    t2 = threading.Thread(target=MyThread2, args=[])
    t1.start()
    t2.start()
    

    带线程:

    import thread
    def MyThread1():
        pass
    def MyThread2():
        pass
    
    thread.start_new_thread(MyThread1, ())
    thread.start_new_thread(MyThread2, ())
    

    thread.start_new_thread 的文档

    【讨论】:

    【解决方案3】:

    我尝试添加另一个 join(),它似乎有效。这是代码

    from threading import Thread
    from time import sleep
    
    def function01(arg,name):
        for i in range(arg):
            print(name,'i---->',i,'\n')
            print (name,"arg---->",arg,'\n')
            sleep(1)
    
    def test01():
        thread1 = Thread(target = function01, args = (10,'thread1', ))
        thread1.start()
        thread2 = Thread(target = function01, args = (10,'thread2', ))
        thread2.start()
        thread1.join()
        thread2.join()
        print ("thread finished...exiting")
    
    test01()
    

    【讨论】:

      【解决方案4】:

      您可以在Thread 构造函数中使用target 参数直接传入一个被调用的函数,而不是run

      【讨论】:

        【解决方案5】:

        你是否重写了 run() 方法?如果你覆盖了__init__,你确定调用基础threading.Thread.__init__()吗?

        在启动两个线程后,主线程是否继续对子线程进行无限期的工作/阻塞/加入,以使主线程执行在子线程完成任务之前不会结束?

        最后,您是否遇到任何未处理的异常?

        【讨论】:

        • 没有未处理的异常,主线程应该运行 30 分钟。我没有覆盖__init__。那么 run() 是必需的吗?谢谢
        • 我刚刚意识到您的示例是def MyThread ( threading.thread )... 我假设那些是类定义。如果您要继承 threading.thread 并使用 target=None 初始化线程对象或省略 target 参数,则需要 run() 的实现。否则,如果您只想在另一个线程中运行一个简单的任务,请参阅 jkp 的答案。
        【解决方案6】:

        Python 3 具有Launching parallel tasks 的功能。这使我们的工作更轻松。

        它适用于thread poolingProcess pooling

        下面给出一个见解:

        ThreadPoolExecutor 示例

        import concurrent.futures
        import urllib.request
        
        URLS = ['http://www.foxnews.com/',
                'http://www.cnn.com/',
                'http://europe.wsj.com/',
                'http://www.bbc.co.uk/',
                'http://some-made-up-domain.com/']
        
        # Retrieve a single page and report the URL and contents
        def load_url(url, timeout):
            with urllib.request.urlopen(url, timeout=timeout) as conn:
                return conn.read()
        
        # We can use a with statement to ensure threads are cleaned up promptly
        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            # Start the load operations and mark each future with its URL
            future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
            for future in concurrent.futures.as_completed(future_to_url):
                url = future_to_url[future]
                try:
                    data = future.result()
                except Exception as exc:
                    print('%r generated an exception: %s' % (url, exc))
                else:
                    print('%r page is %d bytes' % (url, len(data)))
        

        另一个例子

        import concurrent.futures
        import math
        
        PRIMES = [
            112272535095293,
            112582705942171,
            112272535095293,
            115280095190773,
            115797848077099,
            1099726899285419]
        
        def is_prime(n):
            if n % 2 == 0:
                return False
        
            sqrt_n = int(math.floor(math.sqrt(n)))
            for i in range(3, sqrt_n + 1, 2):
                if n % i == 0:
                    return False
            return True
        
        def main():
            with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
                for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
                    print('%d is prime: %s' % (number, prime))
        
        if __name__ == '__main__':
            main()
        

        【讨论】:

          【解决方案7】:

          使用threading实现多线程进程的简单方法

          同样的代码sn-p

          import threading
          
          #function which takes some time to process 
          def say(i):
              time.sleep(1)
              print(i)
          
          threads = []
          for i in range(10):
              
              thread = threading.Thread(target=say, args=(i,))
          
              thread.start()
              threads.append(thread)
          
          #wait for all threads to complete before main program exits 
          for thread in threads:
              thread.join()
          

          【讨论】:

            猜你喜欢
            • 2022-08-20
            • 1970-01-01
            • 2019-06-24
            • 2019-01-10
            • 1970-01-01
            • 1970-01-01
            • 2016-10-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多