Skip to content

fix: error when using graph in multi-threads. #1068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/TensorFlowNET.Core/Device/DeviceSpec.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -7,8 +8,8 @@ namespace Tensorflow.Device
{
public class DeviceSpec
{
private static Dictionary<string, Components> _STRING_TO_COMPONENTS_CACHE = new();
private static Dictionary<Components, string> _COMPONENTS_TO_STRING_CACHE = new();
private static ConcurrentDictionary<string, Components> _STRING_TO_COMPONENTS_CACHE = new();
private static ConcurrentDictionary<Components, string> _COMPONENTS_TO_STRING_CACHE = new();
private string _job;
private int _replica;
private int _task;
Expand Down
41 changes: 41 additions & 0 deletions test/TensorFlowNET.UnitTest/Basics/ThreadSafeTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tensorflow;
using static Tensorflow.Binding;

namespace TensorFlowNET.UnitTest.Basics
{
[TestClass]
public class ThreadSafeTest
{
[TestMethod]
public void GraphWithMultiThreads()
{
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();
Session session = new Session(g);
session.as_default();
var input = tf.placeholder(tf.int32, shape: new Shape(6));
var op = tf.reshape(input, new int[] { 2, 3 });
});
thread.Start();
threads.Add(thread);
}

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