Guest User

Untitled

a guest
Nov 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. /*
  2. * Test the thread_pool class
  3. *
  4. * Compile with g++ thread_pool.cpp thread_pool-test.cpp -pthread
  5. */
  6.  
  7. #include <iostream>
  8. #include <mutex>
  9. #include "thread_pool.h"
  10.  
  11. using namespace std;
  12.  
  13. constexpr size_t threads {0}; // concurrency 0=>platform optimum
  14. constexpr size_t jobs {3}; // number of jobs to do
  15.  
  16. // Each delegate function will take a C-string and an int.
  17. struct Args {
  18. const char *word;
  19. int num;
  20. };
  21.  
  22. // We're going to fire off the thread pool twice
  23. // with two different argument sets.
  24. //
  25. // Using void** avoids typecasting later.
  26. // Alternatively, cast to void** in manifold() call.
  27. void* words[][jobs] = {
  28. { new Args {"One", 1}, new Args {"Two", 2}, new Args {"Three", 3} },
  29. { new Args {"Four", 1}, new Args {"Five", 2}, new Args {"Six", 3} }
  30. };
  31.  
  32. // The delegate funciton accepts a void*
  33. // which it casts to point at its particular argument type.
  34. // Alternatively, cast to ThreadPool::delegate_t in manifold() call.
  35. void say(void* words) {
  36. Args* w(static_cast<Args*>(words));
  37. static mutex m;
  38. lock_guard<mutex> lk(m);
  39.  
  40. for (int i = 0 ; i < w->num ; i++)
  41. cout << w->word << '\t';
  42. cout << endl;
  43. }
  44.  
  45.  
  46. main()
  47. {
  48. // Requesting 0 threads causes the number to be
  49. // equal to the number of CPU cores available on this platform
  50. ThreadPool p(threads);
  51. cout << p.threads << " worker threads are available on this platform.\n\n";
  52.  
  53. // Direct invocation
  54. // minifold will return the number of jobs actually run,
  55. // so the following formula ensures maximum concurrency
  56. p.manifold(ThreadPool::delegate_t(say), words[0], jobs);
  57. cout << endl;
  58.  
  59. // Invocation via lambda expression
  60. // permits use of, e.g., non-static member functions
  61. auto d { [](void* w){say(w);} };
  62. p.manifold(d, words[1], jobs);
  63.  
  64. cout << "\nFinished\n";
  65. // I should probably delete the Args in words[][] now...
  66. }
Add Comment
Please, Sign In to add comment