线程问题

时间:2010-05-04 11:55:20

标签: c multithreading semantics

我想要完成10次,扫描数字并再次打印。我怎么能这样做?

#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;
}

1 个答案:

答案 0 :(得分:3)

我不完全确定你在问什么,但一般来说,如果你想要某些事情发生特定次数,你想要使用for循环,如下所示:

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

我感到困惑的原因是,如果有人在不知道for循环是什么的情况下想出如何创建POSIX线程,这有点奇怪。

相关问题