#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct Shared {
    pthread_mutex_t mutex;
};

struct Shared *shared;

void *worker(void *arg)
{
    printf("worker: trying to lock mutex...\n");

    pthread_mutex_lock(&shared->mutex);

    printf("worker: acquired mutex\n");

    // Do protected work here.

    pthread_mutex_unlock(&shared->mutex);

    printf("worker: finished\n");
    return NULL;
}

int main(void)
{
    pthread_t thread;

    shared = malloc(sizeof(*shared));
    pthread_mutex_init(&shared->mutex, NULL);

    // Lock it before starting worker.
    pthread_mutex_lock(&shared->mutex);

    pthread_create(&thread, NULL, worker, NULL);

    sleep(1);

    printf("main: unlocking mutex\n");

    // Allow worker to proceed.
    pthread_mutex_unlock(&shared->mutex);

    // IMPORTANT:
    // Wait until worker is completely finished.
    pthread_join(thread, NULL);

    printf("main: worker is gone, safe to destroy mutex\n");

    // Nobody can use the mutex anymore.
    pthread_mutex_destroy(&shared->mutex);

    // Now it is safe to release the storage.
    free(shared);

    printf("main: done\n");
    return 0;
}
