Issue
#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;
}
I am expecting that the thread id2 to print the name that I have entered on thread id1.
I know it's the pthread_cond_wait()
doesn't allow the thread id2
to display the name entered on thread id1
but signal()
should be called before wait()
right ?
Is the way of calling wait()
and signal()
methods correct? I am new to linux programming please help me on this.
Solution
If you have a sequential task don't use threads:
#include <stdio.h>
char name[14];
int main() {
printf("Enter Name\n");
scanf("%s",name);
printf("Name: %s\n", name);
return 0
}
You can use a state
variable to ensure that entry()
run before 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;
}
Answered By - Allan Wind