如何将char * argv []传递给pthread_create?

时间:2011-05-01 17:52:41

标签: c

我试图将传递给MAIN线程的任何参数传递给我使用“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;
}

以上代码不起作用,请您告诉我如何在线程中访问ARGV数组,如“argv [0]”等?

2 个答案:

答案 0 :(得分:5)

argv中的mainchar**,而不是char*,因此您应该将其重新投放到threadMainLoop中。

答案 1 :(得分:1)

现在有效......感谢史蒂夫在写作方向的推动......

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;
}