test4.d 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // https://dlang.org/phobos/std_parallelism.html
  2. alias uint8 = ubyte;
  3. alias uint64 = ulong;
  4. import std.stdio;
  5. import std.concurrency : spawn;
  6. import std.parallelism : parallel, defaultPoolThreads;
  7. import core.time : Duration, dur;
  8. import core.thread : Thread;
  9. uint64 fact(uint64 n){
  10. return fact(n, 1);
  11. }
  12. uint64 fact(uint64 n, uint64 a){
  13. if(n == 0){
  14. return a;
  15. }else{
  16. return fact(n - 1, n * a);
  17. }
  18. }
  19. //void test4_worker(uint8 n){
  20. void test4_worker(int n){
  21. writeln("started worker = ", n);
  22. while(true){
  23. //Thread.sleep(dur!"seconds"(120));
  24. //Thread.sleep(dur!"seconds"(3));
  25. auto v20 = fact(20);
  26. //writeln("worker = ", n, " fact 20 = ", v20); // this is sync lock ((
  27. }
  28. Thread.sleep(dur!"seconds"(3));
  29. writeln("stopped worker = ", n);
  30. }
  31. void test4_spawner(){
  32. //uint8 i = 10; // 10 = 1.8 Mb RAM // 255 = 2.9 Mb RAM // 1000 = 6.1 Mb RAM // 10_000 = 47.9 Mb RAM // 100_000 = 180.3 -> 434.4 Mb RAM ,, 161.8 -> 607.7 Mb RAM
  33. //int i = 100_000; // fails
  34. //int i = 30_000;
  35. //int i = 35_000; // fails
  36. /*
  37. while(i > 0){
  38. spawn(&test1_worker, i);
  39. i--;
  40. }
  41. */
  42. writeln("defaultPoolThreads = ", defaultPoolThreads()); // 19
  43. defaultPoolThreads(5);
  44. writeln("defaultPoolThreads = ", defaultPoolThreads()); // 5
  45. //int[] ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  46. int[] ints = [1, 2, 3, 4, 5];
  47. foreach(i, ref num; parallel(ints)){
  48. test4_worker(num);
  49. }
  50. }
  51. /*
  52. > make run
  53. ./vtest2
  54. // 21 threads for 10 elems
  55. // 21 threads for 5 elems too
  56. // 7 threadf for 5 elems
  57. // writeln locking
  58. */