// pthread synchronization example // Copyright 2009 Steven D Wolf (stevewolf6 at gmail dot com) // Copying and distribution of this file, with or without modification, // are permitted in any medium without royalty provided the copyright // notice and this notice are preserved. This file is offered as-is, // without warranty of any kind. // compile with "cc pthread_example.c -o pthread_example -lpthread" #include #include #include typedef struct { pthread_mutex_t parentLock; pthread_mutex_t childLock; pthread_cond_t wait; void* arg; } wrapper_t; void* startRoutine(void* arg) { wrapper_t* wp = (wrapper_t*) arg; printf("child thread created with argument \"%s\"\n", wp->arg); pthread_mutex_lock(&wp->childLock); printf("child thread signaling parent thread\n"); pthread_mutex_lock(&wp->parentLock); pthread_cond_signal(&wp->wait); pthread_mutex_unlock(&wp->parentLock); printf("child thread initializing\n"); sleep(5); printf("child thread waiting for parent signal after initializing\n"); pthread_cond_wait(&wp->wait, &wp->childLock); pthread_mutex_unlock(&wp->childLock); printf("child thread acknowledging to parent thread\n"); pthread_mutex_lock(&wp->parentLock); pthread_cond_signal(&wp->wait); pthread_mutex_unlock(&wp->parentLock); printf("child thread processing\n"); sleep(5); printf("child thread terminating\n"); } main() { wrapper_t threadData; pthread_t tid; int retval; pthread_mutex_init(&threadData.parentLock, NULL); pthread_mutex_init(&threadData.childLock, NULL); pthread_cond_init(&threadData.wait, NULL); threadData.arg = "passed data"; printf("parent thread creating child thread\n"); pthread_mutex_lock(&threadData.parentLock); retval = pthread_create(&tid, NULL, startRoutine, &threadData); if (retval == 0) { printf("parent thread waiting for child signal\n"); pthread_cond_wait(&threadData.wait, &threadData.parentLock); } else { perror("pthread_create"); exit(1); } printf("parent thread received child signal; initializing\n"); pthread_mutex_unlock(&threadData.parentLock); sleep(5); pthread_mutex_lock(&threadData.parentLock); printf("parent thread signaling child thread after initializing\n"); pthread_mutex_lock(&threadData.childLock); pthread_cond_signal(&threadData.wait); pthread_mutex_unlock(&threadData.childLock); printf("parent thread waiting for child thread acknowledge\n"); pthread_cond_wait(&threadData.wait, &threadData.parentLock); printf("parent thread received acknowledge; destroying structure\n"); pthread_mutex_unlock(&threadData.parentLock); pthread_mutex_destroy(&threadData.parentLock); pthread_mutex_destroy(&threadData.childLock); pthread_cond_destroy(&threadData.wait); printf("parent thread processing\n"); sleep(5); printf("parent thread terminating\n"); }