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 2.9 kB

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