为什么我的线程不打印i的每个迭代,而是多次打印一个变量

发布于 2025-01-23 07:57:56 字数 704 浏览 1 评论 0原文

void *phonecall(void *vargp){
        printf("%i\n",*((int *)vargp));
        return NULL;
}

int main(int argc,char **argv){
        int niters=atoi(argv[1]);
        sem_init(&lock,0,1);
        sem_init(&connect_lock,0,7);
        sem_init(&operators,0,4);
        pthread_t threads[niters];
        for(int i=0;i<niters;i++){
                pthread_create(&threads[i], NULL, phonecall, (void *)&i);
        }
        for(int i=0;i<niters;i++){
                pthread_join(threads[i],NULL);
        }
        return 0;
}

如果我输入2 输出通常会导致 2 2

我知道这是我们使用sem_wait和发布的原因,但是我不明白当您使用ID 1创建线程时,为什么不会打印它。也许该订单不同于1和2的订单,但两者都应打印。

void *phonecall(void *vargp){
        printf("%i\n",*((int *)vargp));
        return NULL;
}

int main(int argc,char **argv){
        int niters=atoi(argv[1]);
        sem_init(&lock,0,1);
        sem_init(&connect_lock,0,7);
        sem_init(&operators,0,4);
        pthread_t threads[niters];
        for(int i=0;i<niters;i++){
                pthread_create(&threads[i], NULL, phonecall, (void *)&i);
        }
        for(int i=0;i<niters;i++){
                pthread_join(threads[i],NULL);
        }
        return 0;
}

if i enter make 2
The output often results in
2
2

I know this is the reason we use sem_wait and post but I dont understand when you create thread with id 1, why will it not get printed. Maybe the order is different of 1 and 2 but both should get printed.

In short my basic question is how does the value of vargp change to 2 because 2 threads are create with id 1 and 2 and the output of each thread is often 2 \n 2

Thank You

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方。的韩爷 2025-01-30 07:57:56

您不能确定在下一次迭代之前将执行线程。可能会在执行线程之前执行线程,甚至在执行线程之前循环完成(在这种情况下,正如Barmar所说,此变量将无法访问,您将获得未定义的行为)。
您可以采取的解决问题是使用Malloc分配内存,并将i的值分配给它。
在第一个循环中尝试以下以下内容:

    int* a = malloc(sizeof(int));
    *a = i;
    pthread_create(&threads[i], NULL, phonecall, a);

You can't be sure that threads will be executed before the next iteration. It could happen that threads are executed after the next iteration or even loop finishes before a thread is executed (in that case, as Barmar said, this variable would not be accessible anymore and you would be getting an undefined behavior).
What you can do to solve the issue is allocate memory using malloc and assign the value of i to it.
Try the following inside the first for loop:

    int* a = malloc(sizeof(int));
    *a = i;
    pthread_create(&threads[i], NULL, phonecall, a);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文