TensorFlow多线程例子

# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import threading
import time

def MyLoop(coord, worker_id):
    #使用tf.train.Coordinator类提供的协同工具判断当前线程是否需要停止
    while not coord.should_stop():
        #随机停止所有线程
        if np.random.rand() < 0.1:
            print('stoping from id: %d\n' % worker_id)
            #通知其他线程停止
            coord.request_stop()
        else:
            print('working on id: %d\n' % worker_id)
        time.sleep(1)

coord = tf.train.Coordinator()
#创建5个线程
threads = [threading.Thread(target=MyLoop, args=(coord, i,)) for i in range(5)]
for t in threads: t.start()

#等待所有线程退出
coord.join(threads)

运行结果

F:\Anaconda3\python.exe F:/PycharmProjects/tensorflow/practices/tmp.py
working on id: 0

working on id: 1

working on id: 2

working on id: 3

working on id: 4

working on id: 0

working on id: 4

working on id: 3
stoping from id: 2

working on id: 1



Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/zzldm/article/details/82429058