0

我有一个程序可以进行一些计算等,并使用 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)

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

提前感谢您的任何回复。

4

0 回答 0