#include <stdio.h>
#include <pthread.h>
pthread_mutex_t writer = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t queue = PTHREAD_MUTEX_INITIALIZER;
int global_ctr = 0;
static void *child(void *arg){
while(global_ctr < 10){
if(!pthread_mutex_trylock(&writer)){
if(pthread_mutex_trylock(&queue)){
printf("Child wrote this string\n");
++global_ctr;
}
pthread_mutex_unlock(&queue);
pthread_mutex_unlock(&writer);
}
}
return NULL;
}
int main(){
pthread_t thread;
pthread_create(&thread, NULL, child, NULL);
while(global_ctr < 10){
if(!pthread_mutex_trylock(&writer)){
if(!pthread_mutex_trylock(&queue)){
printf("Parent wrote this string\n");
++global_ctr;
}
pthread_mutex_unlock(&writer);
}
}
return 0;
}
gcc 1.c -lpthread && ./a.out
Parent wrote this string
Child wrote this string
Parent wrote this string
Child wrote this string
Parent wrote this string
Child wrote this string
Parent wrote this string
Child wrote this string
Parent wrote this string
Child wrote this string
Parent wrote this string
Ну, когда наступит линуксокапец, придется, наверное, на BSD пересесть, но там тоже POSIX.