views:

76

answers:

1

I want to be done for 10 times, to scan the number and print it again. How can I do that?

#include <stdio.h>

#include <pthread.h>
#include <semaphore.h>

sem_t m;
int n;

void *readnumber(void *arg)
{
        scanf("%d",&n);
        sem_post(&m);
}

void *writenumber(void *arg)
{   
    //int x =3;
    //while(x>0)
    //{
        //x = x-1;
        sem_wait(&m);
        printf("%d",n);

    //}
}

int main(){
    pthread_t t1, t2;
    sem_init(&m, 0, 0);
    pthread_create(&t2, NULL, writenumber, NULL);
    pthread_create(&t1, NULL, readnumber, NULL);
    pthread_join(t2, NULL);
    pthread_join(t1, NULL);
    sem_destroy(&m);
    return 0;
}
+2  A: 

I'm not entirely sure what you're asking, but generally, if you want something to happen a specific number of times, you want to use a for loop, like so:

for(int i = 0; i < 10; i++) {
//whatever you want to happen 10 times goes here
}

The reason I'm confused is that it's a little odd that someone would have figured out how to create POSIX threads without knowing what a for loop was.

Syntactic
Wish i could +5 this.
cHao