/***************************************************
*--------------------------------------------------
* Creat : 2001. 04. 10 (programed by Cori-Young )
* Site: http://www.byoneself.co.kr
* Update :
*--------------------------------------------------
* Compile : cc -o xxx xxx.c -lpthread -lrt
*--------------------------------------------------
* Machine hardware: sun4u
* OS version: 5.7
* Processor type: sparc
* Hardware: SUNW,Ultra-60
***************************************************/
#include <pthread.h>
#include <stdio.h>
void* compute_thread(void*);
pthread_mutex_t my_sync;
pthread_cond_t rx;
int word_count = 0;
main() {
pthread_t tid;
pthread_attr_t attr;
char hello[] {"Hello, "};
char thread[] {"thread"};
/* Initialize the thread attributes, locks and condition variables */
pthread_attr_init(&attr);
/* Initialize the mutex (default attributes) */
pthread_mutex_init(&my_sync,NULL);
/* Initialize the condition variable (default attr) */
pthread_cond_init(&rx,NULL);
pthread_create(&tid, &attr, compute_thread, thread);
/* We use the word_count to coordinate the threads */
pthread_mutex_lock(&my_sync);
printf(hello);
word_count++;
pthread_cond_signal(&rx);
pthread_mutex_unlock(&my_sync);
/* Lock the mutex again to wait for thread to finish */
pthread_mutex_lock(&my_sync);
while (word_count != 2)
pthread_cond_wait(&rx,&my_sync);
printf("n");
pthread_mutex_unlock(&my_sync);
exit(0);
}
void* compute_thread(void* dummy) {
/* wait until its our turn */
pthread_mutex_lock(&my_sync);
while (word_count != 1)
pthread_cond_wait(&rx,&my_sync);
printf(dummy);
/* set the predicate and signal the other thread */
word_count++;
pthread_cond_signal(&rx);
pthread_mutex_unlock(&my_sync);
return;
} |
|