python - 在多个线程中重用 Tensorflow session 导致崩溃

标签 python python-3.x multithreading tensorflow python-multithreading

背景:

我有一些复杂的强化学习算法,我想在多线程中运行。

问题

当尝试在线程中调用 sess.run 时,我收到以下错误消息:

RuntimeError: session 图为空。在调用 run() 之前向图中添加操作。

重现错误的代码:

import tensorflow as tf

import threading

def thread_function(sess, i):
    inn = [1.3, 4.5]
    A = tf.placeholder(dtype=float, shape=(None), name="input")
    P = tf.Print(A, [A])
    Q = tf.add(A, P)
    sess.run(Q, feed_dict={A: inn})

def main(sess):

    thread_list = []
    for i in range(0, 4):
        t = threading.Thread(target=thread_function, args=(sess, i))
        thread_list.append(t)
        t.start()

    for t in thread_list:
        t.join()

if __name__ == '__main__':

    sess = tf.Session()
    main(sess)

如果我在线程外运行相同的代码,它会正常工作。

有人可以提供一些关于如何正确使用 python 线程的 Tensorflow session 的见解吗?

最佳答案

不仅Session可以是当前线程默认,Graph也可以。 当您传入 session ​​并对其调用 run 时,默认图形将是不同的。

您可以像这样修改您的thread_function 以使其工作:

def thread_function(sess, i):
    with sess.graph.as_default():
        inn = [1.3, 4.5]
        A = tf.placeholder(dtype=float, shape=(None), name="input")
        P = tf.Print(A, [A])
        Q = tf.add(A, P)
        sess.run(Q, feed_dict={A: inn})

但是,我不希望有任何显着的加速。 Python 线程不是它在其他一些语言中的含义,只有某些操作(如 io)会并行运行。对于 CPU 繁重的操作,它不是很有用。多处理可以真正并行运行代码,但您不会共享同一个 session 。

关于python - 在多个线程中重用 Tensorflow session 导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600230/

相关文章:

python-3.x - discord webhook 无法发送空消息

c++ - 从原子内容的意义上说,从匿名管道中读取是原子的吗?

multithreading - macOS 10.13 高塞拉利昂 : [NSGraphicsContext flushGraphics] on background thread has no effect

python - 对嵌套列表进行排序 : Exclude first item from sorting

python - 对数组中的值进行排序 : 'reverse' is an invalid keyword argument for this function

c++ - 使用由 Boost : did not match C++ signature 生成的 Python 模块

python - cupy 会自动使用 cuda 和 GPU 吗?

python - 从 Windows XP 上的压缩标准库将 Python 3.3 嵌入到 C++ 中

python-3.x - Networkx:使用端口连接节点

multithreading - react 性声明 : non blocking code vs blocking code?