Python multithreading implementation executes two while loops at the same time

If you want to execute two while True loops at the same time, you can use multi-threaded threading to achieve it.

full code

#coding=gbk
from time import sleep, ctime 
import threading

def muisc(func):
    while True:
        print 'Start playing: %s! %s' %(func,ctime())
        sleep(2)
 
def move(func):
    while True:
        print 'Start playing: %s! %s' %(func,ctime())
        sleep(5)

def player(name):
    r = name.split('.')[1]
    if r == 'mp3':
        muisc(name)
    else:
        if r == 'mp4':
            move(name)
        else:
            print 'error: The format is not recognized!'

list = ['Love business.mp3','Avatar.mp4']

threads = []
files = range(len(list))

#创建线程
for i in files:
    t = threading.Thread(target=player,args=(list[i],))
    threads.append(t)

if __name__ == '__main__':
    #启动线程
    for i in files:
        threads[i].start()
    for i in files:
        threads[i].join()

    #Main thread
    print 'end:%s' %ctime()

Effect:

This article permanently updates the link address : http://www.linuxidc.com/Linux/2017-03/141331.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325951353&siteId=291194637