Segfault第二次启动pthreads时

时间:2013-04-22 18:05:13

标签: c segmentation-fault pthreads

我有一个程序可以进行一些计算等,并使用pthreads来启动一些线程。这很有效。

但是我需要为基准类型的事物多次启动相同的线程集。当我第二次启动它时,我得到一个段错(核心转储)。

选定代码:

pastebin替代品(缺少第一个互斥线) 应该包括与问题相关的任何事情: http://pastebin.com/5iUsy8L2

function()
{
pthread_mutex_t pmutex;
for (int k = 0; k < 10; k++)
{
    pthread_mutex_lock (&pmutex);

    pthread_t pthreads[CPUTHRDS];
    launch_threads(pthreads);

    /* Unlock and start timer */
    pthread_mutex_unlock (&pmutex);
    tot_time = -msecond();

    /* Join taskthreads when they are done */
    join_threads(pthreads);
    tot_time += msecond();

    //<do something>
}
}

void launch_threads(pthread_t *pthreads)
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

printf("#HOST# Starting Task Threads\n");    

/* Launch the CPU threads */
for (int i = 0; i < CPUTHRDS; i++)
{
    fprintf(stderr, "launchthread %d\n", i);
    int rc = pthread_create(&pthreads[i], &attr, cpu_thread, NULL);
    if (rc) {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
    }
}
printf("#HOST# CPU-Threads started: %d\n", CPUTHRDS);

pthread_attr_destroy(&attr);
}

void join_threads(pthread_t *pthreads)
{
int rc = 0;
for(int i=0; i < CPUTHRDS; i++)
    {
        void *status;
        rc = pthread_join(pthreads[i], &status);
        if (rc) {
            printf("ERROR; return code from pthread_join() is %d\n", rc);
            exit(-1);
        }
        printf("#HOST# Thread %d joined\n", i);
    }
    printf("#HOST# All threads joined\n");
}

void *cpu_thread(void *arg)
{
unsigned long thid = pthread_self();
fprintf(stderr, "started %lu\n", thid);
}

输出

#HOST# Starting Task Threads
launchthread 0
launchthread 1
#HOST# CPU-Threads started: 2
started 46969086678784
started 46969084577536
#HOST# Thread 0 joined
#HOST# Thread 1 joined
#HOST# All threads joined
#HOST# Starting Task Threads
launchthread 0
Segmentation fault (core dumped)

尝试删除对现有变量的任何依赖,但第二次仍然失败。

提前感谢您的回复。

0 个答案:

没有答案