【问题标题】:My loop doesnt run properly in multi-threading我的循环在多线程中无法正常运行
【发布时间】:2017-02-18 02:30:15
【问题描述】:

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

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

我:0
新线程 0
新线程 1
我:1
我: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 t[2]更改为pthread_t t并创建两次,是否可以调用两次pthread_join?

感谢您抽出宝贵时间阅读我的问题。

【问题讨论】:

  • 对于第二个问题:否。第二次调用pthread_create 将覆盖pthread_t 变量。
  • @JoachimPileborg 我明白了!谢谢@GillBates 我的编译器版本是gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4,运行不正确。有问题吗?
  • 运行不正确。”它几乎从不编译器中的错误。
  • @GillBates:运气不好,看起来好像有效。

标签: c multithreading pthreads pthread-join


【解决方案1】:

首先添加一些调试日志:

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 中进行转换,而不仅仅是隐藏通过使编译器静音而导致的编程错误。

【讨论】:

  • 在我的情况下,当 i 在调用 pthread_join 后变为 0 时,我仍然觉得有点奇怪。我没有将i 传递给该函数。但无论如何,感谢您的回答和建议。
  • @ShawnHuang: pthread_join() 需要一个void**,一个指针的地址,它将取消引用它成为一个void*,然后分配给这个void*一个指针值,这可能是8字节,你传递的内存是int,它只有4字节宽。所以其他一些 4 个字节被覆盖。这 4 个字节最有可能属于 i
  • 我在施法时从未考虑过这种副作用。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 2023-03-28
  • 1970-01-01
  • 2013-08-17
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多