What is an example of a concurrent program, with threads / processes?

Suppose we are preparing a meal.

It consists of the following tasks:

  • cook rice
  • cook fish
  • cook soup

A sequential program to cook the meal would be:

int main()
{
    cookRice(2);
    cookFish(2);
    cookSoup(2);
    printf("Lunch Ready");
    return
}

We assert that in this case, all cook* instructions are independent.

Hence, we can execute them in parallel, using processes:

int result;
result = fork();
if (result != 0) { // Parent
    result = fork();
    if (result != 0) { // Parent
        cookRice(2); // Task 2 in main process
    } else {
        cookFish(2); // Child 2 - Task 3
    }
} else { // Child 1 - Task 1
    cookSoup(2);
}

However, we can also do so with threads.

int main()
{
    Thread 1 -> cookRice(2);
    Thread 2 -> cookFish(2);
    Thread 3 -> cookSoup(2);
    join_on(thread1, thread2, thread3);
    return 0;
}