**This is an old revision of the document!**
Table of Contents
Tasks (OpenMP)
Tasks are the OpenMP mechanism for irregular parallelism. parallel for only handles loops with a known iteration count. For work like recursive algorithms, tree traversals, and producer-consumer patterns, #pragma omp task packages a unit of work that any idle thread in the current team can pick up and execute. Tasks are created inside a single region so only one thread generates them while the rest execute them.
#pragma omp parallel #pragma omp single { for (node_t *n = head; n != NULL; n = n->next) { #pragma omp task firstprivate(n) process(n); } }
firstprivate(n) gives each task its own copy of n at the time the task is created. Without it, all tasks would share the same pointer, which moves on as the loop advances. Use #pragma omp taskwait to block until all child tasks spawned in the current scope have finished. Tasks can be nested: a task can itself create more tasks, which is natural for recursive divide-and-conquer.
