简体   繁体   中英

How to pass char* argv[] to pthread_create?

I am trying to pass whatever arguments are passed into the MAIN thread to a "sub thread" I create with "pthread_create".

void *threadMainLoop(void *arg){
    char *arguments = (char*)arg;
    printf("arg 1 - %s\n", arguments[1]);

}

int main(int argc, char *argv[]){
    printf("Start of program execution\n");

    rc = pthread_create(&outboundThread, NULL, threadMainLoop, (void *) argv);
    printf("Thread create rc: %i, %d\n", rc, outboundThread);
    if(rc != 0){
        printf("Thread creation failed\n");
        exit(1);
    }
    pthread_join(outboundThread, NULL);
    return 0;
}

The above code does not work, can you please show me how I can access the ARGV array like "argv[0]" etc in the thread?

The argv in main is a char** , not a char* , and so that's what you should cast it back to in threadMainLoop .

This works now...thanks Steve for the push in the write direction.....

void *threadMainLoop(void *arg){
    char **arguments = (char**)arg;   
    printf("args[0] =%s\n", arguments[0]);
    printf("args[1] =%s\n", arguments[1]);
}

int main(int argc, char *argv[]){
    printf("Start of program execution\n");

    rc = pthread_create(&outboundThread, NULL, threadMainLoop, (void *) argv);
    printf("Thread create rc: %i, %d\n", rc, outboundThread);
    if(rc != 0){
        printf("Thread creation failed\n");
        exit(1);
    }
    pthread_join(outboundThread, NULL);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM