recherche

Maison  >  Questions et réponses  >  le corps du texte

关于下列python多线程代码输出效果的疑问?

下面代码是《python核心编程》关于多线程编程一章中的一个例子:

#!/usr/bin/env python

import threading
from time import sleep, ctime

loops = [ 4, 2 ]

class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        apply(self.func, self.args)

def loop(nloop, nsec):
    print 'start loop', nloop, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()

def main():
    print 'starting at:', ctime()
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        t = MyThread(loop, (i, loops[i]),
        loop.__name__)
        threads.append(t)

    for i in nloops:
        threads[i].start()

    for i in nloops:
        threads[i].join()

    print 'all DONE at:', ctime()

if __name__ == '__main__':
    main()

书上显示的输出结果是这样的

我自己打了一遍,输出结果是这样的

可以看到,我的loop0和loop1的显示内容混合到一起了,这样是对的吗?为什么会这样?

PHP中文网PHP中文网2889 Il y a quelques jours451

répondre à tous(3)je répondrai

  • 巴扎黑

    巴扎黑2017-04-18 09:19:00

    Vous devez le verrouiller ici. La sortie standard est une ressource partagée. Tout le monde peut écrire sur l'écran en même temps, cela peut donc prêter à confusion.
    Vous devez ajouter un verrou mutex ici pour indiquer aux autres sujets que je vais écrire maintenant, alors ne l'écrivez pas encore. Ensuite, une fois que j'ai fini d'écrire, dites aux autres sujets que j'ai fini d'écrire et auxquels vous pouvez postuler. écrire.

    la fonction de boucle s'écrit :

    import threading
    #创建锁
    mutex = threading.Lock()
    
    def loop(nloop, nsec):
        #锁定
        mutex.acquire()
        print 'start loop', nloop, 'at:', ctime()
        sleep(nsec)
        print 'loop', nloop, 'done at:', ctime()
        #释放
        mutex.release()
        

    Tous les codes sont :

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import threading
    from time import sleep, ctime
    
    loops = [ 4, 2 ]
    
    class MyThread(threading.Thread):
        def __init__(self, func, args, name=''):
            threading.Thread.__init__(self)
            self.name = name
            self.func = func
            self.args = args
    
        def run(self):
            apply(self.func, self.args)
    
    # 创建锁
    mutex = threading.Lock()
    
    def loop(nloop, nsec):
        # 锁定
        mutex.acquire()
        print 'start loop', nloop, 'at:', ctime()
        sleep(nsec)
        print 'loop', nloop, 'done at:', ctime()
        # 释放
        mutex.release()
    
    def main():
        print 'starting at:', ctime()
        threads = []
        nloops = range(len(loops))
    
        for i in nloops:
            t = MyThread(loop, (i, loops[i]),
            loop.__name__)
            threads.append(t)
    
        for i in nloops:
            threads[i].start()
    
        for i in nloops:
            threads[i].join()
    
        print 'all DONE at:', ctime()
    
    if __name__ == '__main__':
        main()
    

    répondre
    0
  • PHPz

    PHPz2017-04-18 09:19:00

    Trois points de connaissance sont impliqués ici

    1. Stratégie de planification des threads Python
      Les threads Python sont en fait des threads natifs pris en charge par le système d'exploitation. Le mécanisme multithread de Python est basé sur le mécanisme de thread natif du système d'exploitation. Différents systèmes d'exploitation ont des implémentations différentes. 🎜>

    2. Stratégie de planification des threads Python Windows/Linux

      Recherchez "Stratégie de planification des threads Windows" ou "Stratégie de planification des threads Linux"

    3. verrouillage Python GIL - Processus unique PYTHON sans parallélisme

    Alors tu comprendras

    répondre
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:19:00

    Vous pouvez l'exécuter plusieurs fois et vous comprendrez

    répondre
    0
  • Annulerrépondre