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

typedef struct {
    int *p;
    sem_t ready;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->ready, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->ready);
}

void *thread1(void *data)
{
    data_t *d = data;

    d->p = malloc(sizeof(*d->p));
    *d->p = 42;
    sem_post(&d->ready);
}

void *thread2(void *data)
{
    data_t *d = data;

    sem_wait(&d->ready);
    printf("%d\n", *d->p);
    free(d->p);
}

int main()
{
    pthread_t t1, t2;
    data_t d;

    data_init(&d);

    pthread_create(&t1, NULL, thread1, &d);
    pthread_create(&t2, NULL, thread2, &d);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    data_destroy(&d);

    return 0;
}
