#include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t lockid; pthread_cond_t cvar = PTHREAD_COND_INITIALIZER; char name[14]; void *entry() { pthread_mutex_lock(&lockid); printf("Enter Name\n"); scanf("%s",name); pthread_cond_signal(&cvar); pthread_mutex_unlock(&lockid); pthread_exit(NULL); } void *display() { pthread_mutex_lock(&lockid); pthread_cond_wait(&cvar,&lockid); printf("Name: %s\n",name); pthread_mutex_unlock(&lockid); pthread_exit(NULL); } int main() { pthread_t id1,id2; if(pthread_mutex_init(&lockid,NULL)== 0){ pthread_create(&id1,NULL,&entry,NULL); pthread_create(&id2,NULL,&display,NULL); pthread_join(id1,NULL); pthread_join(id2,NULL); } return 0; }
Espero que el subproceso id2 imprima el nombre que ingresé en el subproceso id1. Sé que es pthread_cond_wait()
no permite que el subproceso id2
muestre el nombre ingresado en el subproceso id1
, pero se debe llamar a signal()
antes de wait()
, ¿verdad? ¿Es correcta la forma de llamar a los métodos wait()
y signal()
? Soy nuevo en la programación de Linux, por favor ayúdenme con esto.
Si tiene una tarea secuencial, no use hilos:
#include <stdio.h> char name[14]; int main() { printf("Enter Name\n"); scanf("%s",name); printf("Name: %s\n", name); return 0 }
Puede usar una variable de state
para asegurarse de que entry()
se ejecute antes display()
:
#include <errno.h> #include <pthread.h> #include <stdio.h> #include <string.h> pthread_mutex_t lockid; pthread_cond_t cvar = PTHREAD_COND_INITIALIZER; char name[14]; enum { START, ENTRY } state = START; #define CHECK(e) { int error = (e); if(error) printf("%s:%d %s", __FILE__, __LINE__, strerror(error)); } #define CHECK2(p, e) { if(p) CHECK(e); } void *entry() { CHECK(pthread_mutex_lock(&lockid)); printf("Enter Name\n"); CHECK2(scanf("%s", name) == EOF, errno); state = ENTRY; pthread_cond_signal(&cvar); CHECK(pthread_mutex_unlock(&lockid)); return 0; } void *display() { CHECK(pthread_mutex_lock(&lockid)); while(state != ENTRY) pthread_cond_wait(&cvar, &lockid); printf("Name: %s\n", name); CHECK(pthread_mutex_unlock(&lockid)); return 0; } int main() { pthread_mutex_init(&lockid, NULL); pthread_t id1, id2; CHECK(pthread_create(&id1, NULL, &entry, NULL)); CHECK(pthread_create(&id2, NULL, &display, NULL)); CHECK(pthread_join(id1,NULL)); CHECK(pthread_join(id2,NULL)); return 0; }