当前位置: 技术问答>linux和unix
如何不用sleep实现线程同步?
来源: 互联网 发布时间:2016-12-14
本文导语: 不使用sleep的话,pthread_cond_wait(&transformed, &lock)还未执行,transform信号就先发出了,就没有用了 如何不用sleep,尽量不用pause,使pthread_cond_wait(&transformed, &lock)执行? #include #include #include #include #include #include ...
不使用sleep的话,pthread_cond_wait(&transformed, &lock)还未执行,transform信号就先发出了,就没有用了
如何不用sleep,尽量不用pause,使pthread_cond_wait(&transformed, &lock)执行?
如何不用sleep,尽量不用pause,使pthread_cond_wait(&transformed, &lock)执行?
#include
#include
#include
#include
#include
#include
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;
int
main(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: %sn", 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 %dn", (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, "endn") == 0)
break;
pthread_mutex_lock(&lock);
pthread_cond_wait(&transformed, &lock);
printf("Output msg:%sn", 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, "endn") == 0)
break;
for(i=0;i