Thread entry point called twice for one thread in array

时间:2019-04-17 01:18:36

标签: c multithreading pthreads

It seems to me that the entry routine is called twice (see duplicated thread 3 is waiting in output below) for one of the threads I create in an array. I suspect it might be a race condition, but wasn't able to fix it. Is there something I missed?

main

pthread_t threads[numthreads];
    fw_t *threadinfo = malloc(sizeof(fw_t) * numthreads);
    int n_thread = file_len / sqrt(numthreads);

    for (int i = 0; i < numthreads; ++i) {
        threadinfo[i].id = i;
        threadinfo[i].n = n_thread;
        printf("i: %i\n", i);
        if (pthread_create(&threads[i], NULL, &fwParallelCommon, (void *)(&threadinfo[i])))
        {
            printf("wasn't able to make the thread :(\n");
        }
    }
    pthread_cond_signal(&cond);

fwParallelCommon

    fw_t *threadinfo = (fw_t *) arg;
    printf("thread %i is waiting\n", threadinfo->id);
    pthread_cond_wait(&cond, &lock);
    printf("created new thread %i\n", threadinfo->id);

Output

dima@DESKTOP-6PQ42D9:~/dva$ ./fw 4 adj1.txt
4 threads
i: 0
i: 1
thread 0 is waiting
i: 2
thread 1 is waiting
i: 3
thread 2 is waiting
thread 3 is waiting
thread 3 is waiting

0 个答案:

没有答案