Guest User

Untitled

a guest
Nov 20th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <omp.h>
  4. #include <queue>
  5.  
  6. class Task {
  7. public:
  8. virtual void execute() = 0;
  9. };
  10.  
  11. class DoFoo : public Task {
  12. public:
  13. DoFoo(int i) : m_i(i) {}
  14. void execute() { printf("foo %03d\n", m_i); }
  15. private:
  16. int m_i;
  17. };
  18.  
  19. class DoBar : public Task {
  20. public:
  21. DoBar(int i) : m_i(i) {}
  22. void execute() { printf("bar %03d\n", m_i); }
  23. private:
  24. int m_i;
  25. };
  26.  
  27. std::queue<Task *> task_queue;
  28.  
  29. int main(int argc, char *argv[]) {
  30. int num_threads;
  31. if (argc < 2)
  32. num_threads = 1 + omp_get_max_threads(); // 1 for the master, which will mostly sleep
  33. else
  34. num_threads = std::max(atoi(argv[1]), 1);
  35.  
  36. bool production = (bool)1;
  37. #pragma omp parallel num_threads(num_threads) shared(production)
  38. {
  39. if (omp_get_thread_num() == 0)
  40. {
  41. printf("%d threads have been created\n", omp_get_num_threads());
  42. for (int i = 0; i < 100; ++i) {
  43. printf("Pushing task #%d\n", i);
  44. task_queue.push(new DoFoo(i));
  45. }
  46. for (int i = 100; i < 200; ++i) {
  47. printf("Pushing additional task #%d\n", i);
  48. task_queue.push(new DoBar(i));
  49. }
  50. #pragma omp atomic
  51. production ^= 1;
  52. } else {
  53. while (true) {
  54. Task *t;
  55. #pragma omp critical
  56. {
  57. if (task_queue.size()) {
  58. t = task_queue.front();
  59. task_queue.pop();
  60. } else
  61. t = NULL;
  62. }
  63. if (t) {
  64. t->execute();
  65. delete t;
  66. } else if (!production)
  67. break;
  68. }
  69. }
  70. }
  71.  
  72. printf("Work finished\n");
  73.  
  74. return 0;
  75. }
Add Comment
Please, Sign In to add comment