如何不用sleep实现线程同步?
不使用sleep的话,pthread_cond_wait(&transformed, &lock)还未执行,transform信号就先发出了,就没有用了
如何不用sleep,尽量不用pause,使pthread_cond_wait(&transformed, &lock)执行?
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <signal.h>#include <pthread.h>void *sender(void *);void *receiver(void *);char msg[60];int tfed;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t inputed = PTHREAD_COND_INITIALIZER;pthread_cond_t transformed = PTHREAD_COND_INITIALIZER;intmain(int argc, char **argv) {int err;void *sent;pthread_t sthd, rthd;err = pthread_create(&rthd, NULL, receiver, NULL);err = pthread_create(&sthd, NULL, sender, NULL);if (err != 0) { fprintf(stderr, "can't create sender thread: %s\n", strerror(err)); exit(1);}pthread_join(sthd, &sent);pthread_join(rthd, &sent);pthread_mutex_destroy(&lock);pthread_cond_destroy(&inputed);pthread_cond_destroy(&transformed);printf("Sent Messsages %d\n", (int)sent);}void *sender(void *arg){ FILE *fp; char line[132], output[132]; int sent_msg=0, sender_pid; while (1) { pthread_mutex_lock(&lock); fgets(msg, sizeof(msg), stdin); pthread_mutex_unlock(&lock); pthread_cond_signal(&inputed); sent_msg++; if (strcmp(line, "end\n") == 0) break; pthread_mutex_lock(&lock); pthread_cond_wait(&transformed, &lock); printf("Output msg:%s\n", msg); pthread_mutex_unlock(&lock); } pthread_exit((void *)sent_msg); }void *receiver(void *arg){ FILE *fp; char line[132], output[132]; int sent_msg=0, i; while(1){ pthread_mutex_lock(&lock); pthread_cond_wait(&inputed, &lock); strcpy(line, msg); if (strcmp(msg, "end\n") == 0) break; for(i=0;i<strlen(line);i++) msg[i]= toupper(line[i]); msg[i]='\0'; strcpy(output, msg); pthread_mutex_unlock(&lock); //printf("Transformed msg:%s\n", output); sent_msg++; sleep(1); pthread_cond_signal(&transformed); } pthread_exit((void *)sent_msg); }