不使用sleep的话,pthread_cond_wait(&transformed, &lock)还未执行,transform信号就先发出了,就没有用了
如何不用sleep,尽量不用pause,使pthread_cond_wait(&transformed, &lock)执行?
- C/C++ code
#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); }
------解决方案--------------------------------------------------------
执行太快了就放弃cpu的时间片,sleep(0)也可以
------解决方案--------------------------------------------------------
当消费者从生产者那里取走了货物,并使用后,生产者才能再生产
如果我没有理解错,你想表达这样的意思,那么多线程的意义何在呢?
要实现你的代码,需要增加标志,表示信号是否已经发出,比如,a 等待 b的信号
a {
pthread_mutex_lock(&lock);
if (sended == 0) {
pthread_cond_wait(&sig, &lock);
}
pthread_mutex_unlock(&lock);
}
b {
pthread_mutex_lock(&lock);
sended = 1;
pthread_cond_signal(&sig);
pthread_mutex_unlock(&lock);
}