Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cstdlib>
- #include <omp.h>
- #include <queue>
- class Task {
- public:
- virtual void execute() = 0;
- };
- class DoFoo : public Task {
- public:
- DoFoo(int i) : m_i(i) {}
- void execute() { printf("foo %03d\n", m_i); }
- private:
- int m_i;
- };
- class DoBar : public Task {
- public:
- DoBar(int i) : m_i(i) {}
- void execute() { printf("bar %03d\n", m_i); }
- private:
- int m_i;
- };
- std::queue<Task *> task_queue;
- int main(int argc, char *argv[]) {
- int num_threads;
- if (argc < 2)
- num_threads = 1 + omp_get_max_threads(); // 1 for the master, which will mostly sleep
- else
- num_threads = std::max(atoi(argv[1]), 1);
- bool production = (bool)1;
- #pragma omp parallel num_threads(num_threads) shared(production)
- {
- if (omp_get_thread_num() == 0)
- {
- printf("%d threads have been created\n", omp_get_num_threads());
- for (int i = 0; i < 100; ++i) {
- printf("Pushing task #%d\n", i);
- task_queue.push(new DoFoo(i));
- }
- for (int i = 100; i < 200; ++i) {
- printf("Pushing additional task #%d\n", i);
- task_queue.push(new DoBar(i));
- }
- #pragma omp atomic
- production ^= 1;
- } else {
- while (true) {
- Task *t;
- #pragma omp critical
- {
- if (task_queue.size()) {
- t = task_queue.front();
- task_queue.pop();
- } else
- t = NULL;
- }
- if (t) {
- t->execute();
- delete t;
- } else if (!production)
- break;
- }
- }
- }
- printf("Work finished\n");
- return 0;
- }
Add Comment
Please, Sign In to add comment