先感受一下队列之美
import tensorflow as tf
q = tf.FIFOQueue(2, "int32") # 创建一个先进先出队列
# 队列中最多可以保存两个元素,并指定类型为整数
init = q.enqueue_many(([0, 10],))
x = q.dequeue()
y = x + 1
q_inc = q.enqueue([y])
with tf.Session() as sess:
init.run()
for _ in range(5):
v, _ = sess.run([x, q_inc])
print(v)
一个多线程的示例
import tensorflow as tf
import numpy as np
import threading
import time
def MyLoop(coord, worker_id):
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) # 等待所有线程退出
启动多线程
import tensorflow as tf
queue = tf.FIFOQueue(100, "float")
enqueue_op = queue.enqueue([tf.random_normal([1])])
qr = tf.train.QueueRunner(queue, [enqueue_op] * 5)
# 这表示启动5个线程
tf.train.add_queue_runner(qr)
out_tensor = queue.dequeue()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,
coord=coord)
for _ in range(6):
print(sess.run(out_tensor)[0])
coord.request_stop()
coord.join(threads)