how to use tensorflow graphs in multithread？valueerror：tensor a must be from the same graph as tensor b！ I am doing instance detect and image retrieval task by Keras and Tensorflow as backend.

I plan to use multi thread to load two model, I load maskrcnn in a thread and load mobile net in another one.

I load the maskrcnn in a thread successfully, but I failed to load mobile net in another thread, and:


  show:ValueError: tensor a must be from the same graph as tensor b.


The code is as below:

Merge.py

from keras import backend as K

g1=tf.Graph()
g2=tf.Graph()
sess1=tf.Session(graph=g1)
sess2=tf.Session(graph=g2)

def intiMaskrcnn():
     with g1.as_default():
           with sess1.as_default():
                   Model1=........

def instanceDetect():
       K.set_session(sess1)
       with g1.as_default():
             Model1.predit()
             ............


def intiMobilenet():
     with g2.as_default():
           with sess2.as_default():
                   Model2=........

def Retrieval():
       K.set_session(sess2)
       with g2.as_default():
             Model2.predit()
             ............


Thread1.py

intiMaskrcnn()
instanceDetect()


Thread2.py

intiMobilenet()
Retrieval()


Where am I going wrong?
TensorFlow stores all operations on an operational graph. This graph defines what functions output to where, and it links it all together so that it can follow the steps you have set up in the graph to produce your final output. If you try to input a Tensor or operation on one graph into a Tensor or operation on another graph it will fail. Everything must be on the same execution graph.

Try to use 

tf.reset_default_graph() 


to reset the tf graph once it executes.

For keras use K.clear_session().

For more details about the keras and tensorflow interface view Keras documentation blog.https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html this helps you a lot.