#include /* POSIX 1003.1c threads */ #include /* standard input/output */ pthread_mutex_t mutex; /* Wechselseitiger Ausschluss */ pthread_cond_t cond; /* Bedingungsvariable */ pthread_key_t key; /* Thread-specifischer Datenschluessel */ int counter = 0; /* Thread-Zaehler */ int printed = 0; /* Hat Thread 0 bereits gedruckt? */ void print(void) { char *string = (char*)pthread_getspecific(key); printf("%s", string); } void *thread(void *arg) { int number; /* 0 = hello, 1 = world */ pthread_mutex_lock(&mutex); number = counter; counter++; pthread_mutex_unlock(&mutex); pthread_setspecific(key, ((char**)arg)[number]); if (number == 0) { print(); pthread_mutex_lock(&mutex); printed++; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } else { pthread_mutex_lock(&mutex); while (printed == 0) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); print(); } return(0); } int main() { char* strings[] = {"hello ", "world\n"}; pthread_t thread1, thread2; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_key_create(&key, NULL); pthread_create(&thread1, NULL, thread, strings); pthread_create(&thread2, NULL, thread, strings); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return(0); }