首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果我在循环中创建线程,前两个线程不会被执行

如果我在循环中创建线程,前两个线程不会被执行
EN

Stack Overflow用户
提问于 2013-06-09 15:27:11
回答 2查看 93关注 0票数 0

我在我的Windows7机器上使用MINGW进行POSIX线程编码。

考虑下面的简单代码:

代码语言:javascript
复制
#include <stdio.h>
#include <pthread.h>
#include <process.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
    long tid;
        tid = (long)threadid;
    printf("Hello Dude...!!!\t I am thread no #%ld\n",tid);
    pthread_exit(NULL);
}
int main()
{
    pthread_t thread[NUM_THREADS];
    int rc;
    long t;
    for(t=0;t<NUM_THREADS;t++)
    {
        printf("Inside the Main Thread...\nSpawning Threads...\n");
        rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t);
        if(rc)
        {
            printf("ERROR: Thread Spawning returned code %d\n",rc);
            exit(-1);
        }
    }
    return 0;
}

当上面的程序在我的系统中执行时,它会显示以下输出:

代码语言:javascript
复制
Inside the Main Thread...
Spawning Threads...
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!!         I am thread no #0
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!!         I am thread no #1
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!!         I am thread no #2
Inside the Main Thread...
Spawning Threads...

这个程序应该会产生5个线程。但它只创建了2个线程。前两行和最后两行表明即将调用pthread_create()例程。由于"rc“变量不是"1”,因此在线程创建过程中毫无疑问会出现任何错误,否则它将命中"if(rc)“部分。

那么错误在哪里呢?或者它是与我的windows机器有关的东西。

EN

回答 2

Stack Overflow用户

发布于 2013-06-09 15:30:28

没有错误。

你的程序在其他线程有机会输出任何东西之前就退出了,退出你的程序会杀死它的所有线程。

如果你想让所有的线程都正常的完成,你需要pthread_join所有的线程。

票数 1
EN

Stack Overflow用户

发布于 2013-06-09 15:30:15

实际上,真正的问题是,当你的main结束时,你的程序也会结束。在从main返回之前,您应该对它们执行pthread_join操作。其他线程没有机会在main退出之前运行,这会占用整个进程空间(以及未运行的线程)。

代码语言:javascript
复制
for(t=0;t<NUM_THREADS;t++)
{
    printf("Inside the Main Thread...\nSpawning Threads...\n");
    rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t);
    if(rc)
    {
        printf("ERROR: Thread Spawning returned code %d\n",rc);
        exit(-1);
    }
}

/* add this and you're golden! */
for(t=0; t<NUM_THREADS;t++) {
    pthread_join(thread[t], NULL);
}

以下是我最初的答案,也是一个很好的建议:

不要将long作为void*传递。传递它的地址。如果需要,可以在每次循环中复制一份,以便传递并在以后释放它。

代码语言:javascript
复制
long thread_data[NUM_THREADS];
for(t=0;t<NUM_THREADS;t++)
    {
        thread_data[t] = t;
        printf("Inside the Main Thread...\nSpawning Threads...\n");
        rc=pthread_create(&thread[t],NULL,PrintHello,(void*)&(thread_data[t]));
        if(rc)
        {
            printf("ERROR: Thread Spawning returned code %d\n",rc);
            exit(-1);
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17007384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档