How to pass arguments in pthread_create() in c

55 views Asked by At

I want to implement bucket sort with multi-threading. So I create an array and separate it into several subsequence, the subsequence is then passed to the pthread_create() by passing the starting address of each subsequence and its length into threadFunc(). But I always got the values in first few subsequences skipped when I tried to print then out, what is the reason for this? Any help would be appreciated!

Following is part of my code:

struct thread_argv
{
    unsigned int * startAddr;
    long fragSize;
    pthread_t * tid;
};

unsigned int * ptr = intarr;

thread_argv1.fragSize = fragSize;

for (i=0; i<numThread; i++){
    thread_argv1.startAddr = ptr;
    thread_argv1.tid = tids[i];
    pthread_create(tids[i], NULL, threadFunc, (void *) &thread_argv1);
    ptr += fragSize;
}

void * threadFunc(void * thread_argv){
    struct thread_argv * argv = (struct thread_argv *) thread_argv;

    for(int i=0; i<argv->fragSize; i++){
        printf("Tid: %ld, Address: %ld, Value: %u\n", argv->tid, argv->startAddr, *argv->startAddr);
        argv->startAddr++;
    }
}

I have tried test the value in each address (starting addr of each subsequence) before passing into the pthread_create(), and the values are correct. But when I want to print them out in the child thread, the values are as expected (the values of the first two subsequences are skipped).Output

0

There are 0 answers