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.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. }
  18. [TestMethod, Ignore("Has to be tested manually.")]
  19. public void SessionCreation()
  20. {
  21. lock (_singlethreadLocker)
  22. {
  23. ops.uid(); //increment id by one
  24. //the core method
  25. tf.peak_default_graph().Should().BeNull();
  26. using (var sess = tf.Session())
  27. {
  28. var default_graph = tf.peak_default_graph();
  29. var sess_graph = sess.graph;
  30. sess_graph.Should().NotBeNull();
  31. default_graph.Should().NotBeNull()
  32. .And.BeEquivalentTo(sess_graph);
  33. var (graph, session) = Parallely(() => (tf.get_default_graph(), tf.get_default_session()));
  34. graph.Should().BeEquivalentTo(default_graph);
  35. session.Should().BeEquivalentTo(sess);
  36. }
  37. }
  38. }
  39. T Parallely<T>(Func<T> fnc)
  40. {
  41. var mrh = new ManualResetEventSlim();
  42. T ret = default;
  43. Exception e = default;
  44. new Thread(() =>
  45. {
  46. try
  47. {
  48. ret = fnc();
  49. }
  50. catch (Exception ee)
  51. {
  52. e = ee;
  53. throw;
  54. }
  55. finally
  56. {
  57. mrh.Set();
  58. }
  59. }).Start();
  60. if (!Debugger.IsAttached)
  61. mrh.Wait(10000).Should().BeTrue();
  62. else
  63. mrh.Wait(-1);
  64. e.Should().BeNull(e?.ToString());
  65. return ret;
  66. }
  67. void Parallely(Action fnc)
  68. {
  69. var mrh = new ManualResetEventSlim();
  70. Exception e = default;
  71. new Thread(() =>
  72. {
  73. try
  74. {
  75. fnc();
  76. }
  77. catch (Exception ee)
  78. {
  79. e = ee;
  80. throw;
  81. }
  82. finally
  83. {
  84. mrh.Set();
  85. }
  86. }).Start();
  87. mrh.Wait(10000).Should().BeTrue();
  88. e.Should().BeNull(e.ToString());
  89. }
  90. }
  91. }