【问题标题】:problem with threads线程问题
【发布时间】:2011-02-15 10:32:59
【问题描述】:

我想完成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;
}

【问题讨论】:

标签: c multithreading semantics


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2022-01-08
    • 2010-12-13
    相关资源
    最近更新 更多