You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

EnforcedSinglethreadingTests.cs 3.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using FluentAssertions;
  9. using Microsoft.VisualStudio.TestTools.UnitTesting;
  10. using NumSharp;
  11. using Tensorflow;
  12. using Tensorflow.Util;
  13. using static Tensorflow.Binding;
  14. namespace TensorFlowNET.UnitTest.NativeAPI
  15. {
  16. [TestClass]
  17. public class EnforcedSinglethreadingTests : CApiTest
  18. {
  19. private static readonly object _singlethreadLocker = new object();
  20. /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
  21. public EnforcedSinglethreadingTests()
  22. {
  23. ops.IsSingleThreaded = true;
  24. }
  25. [TestMethod, Ignore("Has to be tested manually.")]
  26. public void SessionCreation()
  27. {
  28. lock (_singlethreadLocker)
  29. {
  30. ops.IsSingleThreaded.Should().BeTrue();
  31. ops.uid(); //increment id by one
  32. //the core method
  33. tf.peak_default_graph().Should().BeNull();
  34. using (var sess = tf.Session())
  35. {
  36. var default_graph = tf.peak_default_graph();
  37. var sess_graph = sess.GetPrivate<Graph>("_graph");
  38. sess_graph.Should().NotBeNull();
  39. default_graph.Should().NotBeNull()
  40. .And.BeEquivalentTo(sess_graph);
  41. var (graph, session) = Parallely(() => (tf.get_default_graph(), tf.get_default_session()));
  42. graph.Should().BeEquivalentTo(default_graph);
  43. session.Should().BeEquivalentTo(sess);
  44. }
  45. }
  46. }
  47. T Parallely<T>(Func<T> fnc)
  48. {
  49. var mrh = new ManualResetEventSlim();
  50. T ret = default;
  51. Exception e = default;
  52. new Thread(() =>
  53. {
  54. try
  55. {
  56. ret = fnc();
  57. } catch (Exception ee)
  58. {
  59. e = ee;
  60. throw;
  61. } finally
  62. {
  63. mrh.Set();
  64. }
  65. }).Start();
  66. if (!Debugger.IsAttached)
  67. mrh.Wait(10000).Should().BeTrue();
  68. else
  69. mrh.Wait(-1);
  70. e.Should().BeNull(e?.ToString());
  71. return ret;
  72. }
  73. void Parallely(Action fnc)
  74. {
  75. var mrh = new ManualResetEventSlim();
  76. Exception e = default;
  77. new Thread(() =>
  78. {
  79. try
  80. {
  81. fnc();
  82. } catch (Exception ee)
  83. {
  84. e = ee;
  85. throw;
  86. } finally
  87. {
  88. mrh.Set();
  89. }
  90. }).Start();
  91. mrh.Wait(10000).Should().BeTrue();
  92. e.Should().BeNull(e.ToString());
  93. }
  94. }
  95. }