1. 程式人生 > >python生成器模擬多工小案例

python生成器模擬多工小案例

#模擬多工

def neteasy_musice(duration):
    time = 0
    while time <= duration:
        print('music to %d minute'%time)
        time += 1
        yield None
    raise StopIteration()
def youku_movie(duration):
    time = 0
    while time <= duration:
        print('movie to %d minute'%time)
        time += 1
        yield None
    raise StopIteration()
def main():
    music_iter,movie_iter = neteasy_musice(10),youku_movie(20)
    music_stop = False
    movie_stop = False
    while True:
        try:
            next(music_iter)
        except StopIteration:
            if not music_stop:
                print('music end')
            music_stop = True
        try:
            next(movie_iter)
        except StopIteration:
            if not movie_stop:
                print('movie end')
            movie_stop = True
        if music_stop and movie_stop:
            break
if __name__ == '__main__':
    main()