• 向 pthread 传递多个参数的方法


    2007年11月20日 星期二

    pthread_create 傳遞參數的用法

    最近,又開始寫 socket 的程式.
    有別於以前用 select 或最早的 heavy-weight 的 fork 方式.
    這次改用 pthread 來 handle server 端所收到的 request .
    不過, 有一個問題, 如何傳參數給 thread 的 handler
    man pthread_create 可以看到只有 4th argument 可以應用.
    至於怎麼用. 找了以前的 sample code, 原來,做 casting 就可以.

    string 沒問題, 如果是傳 integer 就這樣寫..

    void pfunc ( void *data)
    {
    int i = (int)data;
    ...
    }

    main()
    {
    int ival=100;
    pthread_t th;
    ...
    pthread_create( &th, NULL, pfunc, (void *) ival );
    }

    如遇到多個參數. 就包成 struct , 傳 pointer 過去吧 ~

    struct test
    {
    int no;
    char name[80];
    };

    void pfunc ( void *data)
    {
    struct test tt = (struct test*)data;
    ...
    }

    main()
    {
    struct test itest;
    pthread_t th;
    ...
    itest.no=100;
    strcpy(itest.name,"Hello");
    ...
    pthread_create( &th, NULL, pfunc, (void *)& itest );
    ..
    }

     

  • 相关阅读:
    clickhouse使用docker安装单机版
    nacos使用docker安装单机版
    第三周学习进度
    第二周学习进度
    二柱子四则运算定制版
    课堂测试小程序
    学习进度
    阅读计划
    自我介绍
    寻找水王
  • 原文地址:https://www.cnblogs.com/cy163/p/1269930.html
Copyright © 2020-2023  润新知