亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

由pthread_create()調用的函數有多個參數?

由pthread_create()調用的函數有多個參數?

C
瀟瀟雨雨 2019-12-20 10:50:26
我需要將多個參數傳遞給要在單獨線程上調用的函數。我已經讀到,執行此操作的典型方法是定義一個struct,向該函數傳遞一個指向該struct的指針,然后將其取消引用以用作參數。但是,我無法使它正常工作:#include <stdio.h>#include <pthread.h>struct arg_struct {    int arg1;    int arg2;};void *print_the_arguments(void *arguments){    struct arg_struct *args = (struct arg_struct *)args;    printf("%d\n", args -> arg1);    printf("%d\n", args -> arg2);    pthread_exit(NULL);    return NULL;}int main(){    pthread_t some_thread;    struct arg_struct args;    args.arg1 = 5;    args.arg2 = 7;    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {        printf("Uh-oh!\n");        return -1;    }    return pthread_join(some_thread, NULL); /* Wait until thread is finished */}輸出應為:57但是當我運行它時,我實際上得到了:141921115-1947974263有人知道我在做什么錯嗎?
查看完整描述

3 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

因為你說


struct arg_struct *args = (struct arg_struct *)args;


代替


struct arg_struct *args = arguments;


查看完整回答
反對 回復 2019-12-20
?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

使用


struct arg_struct *args = (struct arg_struct *)arguments;

代替


struct arg_struct *args = (struct arg_struct *)args;


查看完整回答
反對 回復 2019-12-20
?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

main()有自己的線程和堆棧變量。為堆中的“ args”分配內存或使其成為全局內存:


struct arg_struct {

    int arg1;

    int arg2;

}args;


//declares args as global out of main()

然后,當然,改變從引用args->arg1到args.arg1等。


查看完整回答
反對 回復 2019-12-20
  • 3 回答
  • 0 關注
  • 655 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號