#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
const int kNumThreads = 2;
pthread_t tid[kNumThreads];
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char go = 0;
void *thread_free(void *p) {
pthread_mutex_lock(&mutex);
while (!go)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
free(p);
return 0;
}
void child(void) {
void *p = malloc(16);
for (int i = 0; i < kNumThreads; i++)
pthread_create(&tid[i], 0, thread_free, p);
pthread_mutex_lock(&mutex);
go = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
for (int i = 0; i < kNumThreads; i++)
pthread_join(tid[i], 0);
}
int main(int argc, char **argv) {
const int kChildren = 40;
pid_t pid;
for (int i = 0; i < kChildren; ++i) {
pid = fork();
if (pid < 0) {
exit(1);
} else if (pid == 0) {
child();
exit(0);
} else {
int status;
wait(&status);
if (status == 0)
exit(1);
}
}
return 0;
}