c - 我的循环在多线程中无法正常运行

标签 c multithreading pthreads pthread-join

我尝试编写一个多线程程序,遇到了一些问题。

在我运行 main.c 之后,我得到了

i: 0
new thread 0
new thread 1
i: 1
i: 1

//main.c
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
void* routine(void* arg)
{
    int id = (intptr_t) arg;
    printf("new thread %d\n", id);
    pthread_exit((void*)(intptr_t) id);
}
int main()
{
    pthread_t t[2];
    int i;
    for(i=0; i<2; i++)
    {
        int ret = pthread_create (&t[i], NULL, &routine,  (void *)(intptr_t) i);
        if(ret != 0) {
            printf("Error: pthread_create() failed\n");
            return -1;
        }
    }
    int id;
    /////////here
    for(i=0; i<2; i++)
    {
        printf("i: %d\n",i);
        pthread_join(t[i], (void **)&id);
    }
    /////////here
    pthread_exit(NULL);
}

我的问题是

  • 为什么最后一个循环运行三次?
  • 如果我将 pthread_t[2] 更改为 pthread_t 并创建两次,是否可以调用 pthread_join 两次?

感谢您花时间阅读我的问题。

最佳答案

首先添加一些调试日志:

int id;
for(i=0; i<2; i++)
{
    printf("i: %d\n",i);
    pthread_join(t[i], (void **)&id);
    printf("id[%d]: %d\n", i, id);
}

重新运行并记住输出。

然后改成这样

int id;
for(i=0; i<2; i++)
{
    void * pv;   
    printf("i: %d\n",i);
    pthread_join(t[i], &pv); /* Add error checking here! */
    id = (intptr_t) pv;
    printf("id: %d\n", id);
}

重新运行并与之前的版本进行比较。


根据经验:

如果面对看似需要在 C(而不是 C++)中进行转换,请务必三思,因为只有非常、非常、非常罕见的情况需要在 C 中进行转换,而不仅仅是隐藏通过使编译器静音来造成编程错误。

关于c - 我的循环在多线程中无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39945217/

相关文章:

c - MPI_ERR_RANK : invalid rank with cluster

java - 将 Spring Batch 分区配置为处理器和写入器,同时从分区中排除读取器

multithreading - 测试高并发工作线程系统的正确方法是什么?

c++ - 是否有生产者消费者以外的设计模式来描述这种模式?

编译器在返回 char 指针数组时提示

c - 我应该在 c 中使用有限输入的 fgets 还是 scanf?

c - 中缀到后缀函数错误 : control may reach end of non-void function

java - 如何在 Java 中暂停/恢复 ExecutorService 中的所有线程?

c - pthread_join 返回 NULL 地址

c - 如果在 linux 中花费的时间超过阈值时间,如何终止子线程