views:

123

answers:

3

Write program that has two threads one is reading numbers from the user and the other is printing them such that the first thread reads a new number only after it has been printed by the second thread. Declare one global varaible to use for reading and printing.

#include <stdio.h>

#include <pthread.h>
#include <semaphore.h>
sem_t m;
void *f1(void *arg)
{
    sem_wait(&m);
    scanf("%d",&n);
}

void *f2(void *arg)
{   
    printf("Second\n");
}


int main(){

    int n;
    pthread_t t1, t2;
    sem_init(&m, 0, 1);
    pthread_create(&t1, NULL, f1, NULL);
    pthread_create(&t2, NULL, f2, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    sem_destroy(&m);
    sem_destroy(&m2);
    return 0;

}
+3  A: 

I think you should first try to do it by yourself, then if you really need help, ask a real question here and explain what you don't manage to do.

Also, you should first read a tutorial about using threads if you haven't (this could be a good site to start with).

Shelldon
i have tried the code below
Nadeem
A: 

include

include

include

sem_t m; void *f1(void *arg) { sem_wait(&m); scanf("%d",&n); } void *f2(void *arg) {
printf("Second\n"); }

int main(){

int n;
pthread_t t1, t2;
sem_init(&m, 0, 1);
pthread_create(&t1, NULL, f1, NULL);
pthread_create(&t2, NULL, f2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&m);
sem_destroy(&m2);
return 0;

}

Nadeem
Please edit the question, rather than adding a new answer.
Hasturkun
A: 

Do you really want your thread functions to return after running just once?

I don't see where n is defined for use in f1.

There's more, but you should address these before moving on.

nategoose