SciSharp / TensorFlow.NET

.NET Standard bindings for Google's TensorFlow for developing, training and deploying Machine Learning models in C# and F#.
https://scisharp.github.io/tensorflow-net-docs
Apache License 2.0
3.2k stars 514 forks source link

[BUG Report]: v0.100.5 is not thread safe anymore #1066

Closed Superpiffer closed 1 year ago

Superpiffer commented 1 year ago

Description

I have this exception in a multi thread application: image

Apparently different threads tries to modify this Dictionary: https://github.com/SciSharp/TensorFlow.NET/blob/cd64ea96f31cce51405664023023db94de45f1e7/src/TensorFlowNET.Core/Device/DeviceSpec.cs#L10

Reproduction Steps

Create more than one thread with a new instance of Session per thread:

private static void TestThreads()
{
    List<Thread> threads = new List<Thread>();

    const int THREADS_COUNT = 5;

    for(int t = 0; t < THREADS_COUNT; t++)
    {
        Thread thread = new Thread(() =>
        {
            Graph g = new Graph();
            g.Import("model.pb");
            Session session = new Session(g);
        });
        thread.Start();
        threads.Add(thread);
    }

    threads.ForEach(t => t.Join());
}

Known Workarounds

I can bypass this issue using a ConcurrentDictionary, but I don't know if that's an ideal solution.

Configuration and Other Information

Tensorflow.NET v0.100.5 .NET 6.0

Oceania2018 commented 1 year ago

ConcurrentDictionary is the good approach. @AsakusaRinne