B10 - functions in parallel regions

thread-safe

  • a function that can be called concurrently by multiple threads without causing incorrect behaviour due to unsynchronized shared state

// thread-safe
int square(int x) {
    int result = x * x;
    return result;
}

//not thread-safe
int counter = 0;  // global variable
void increment() {
    counter++; //concurrent increments cause data race
}
int x = 10;

void work() {
    int y = 5;
    x += y;
}

#pragma omp parallel private(x)
{
    work();  // x in the function will not be private
}
#include <stdio.h>
#include <omp.h>

int counter = 0;

#pragma omp threadprivate(counter)

void increment() {
    counter++;
}

int main() {
    #pragma omp parallel num_threads(4)
    {
        increment();
        printf("Thread %d: counter = %d\n",
               omp_get_thread_num(), counter);
    }
    return 0;
}
// thread-safe if len(a) >= 100
void update(int a[], int i) {
    a[i] = a[i] + 1;  // each iteration modifies a different element
}

// not thread-safe
void update(int a[], int i) {
    a[i] = a[i] + a[i-1]; // a[i-1] is modified by a different thread
}
int main() {
    #pragma omp parallel
    {
        return 0;  // invalid
    }
}