zoukankan      html  css  js  c++  java
  • pthread_create传递参数



    #include <iostream>
    
    #include <pthread.h>
    
    using namespace std;
    
    pthread_t thread;
    
    void *fn(void *arg)
    {
        int i = *(int *)arg;
        cout<<"i = "<<i<<endl;
    
        return ((void *)0);
    }
    
    int main()
    {
        int err1;
        int i=10;
    
        err1 = pthread_create(&thread, NULL, &fn, &i);
        pthread_join(thread, NULL);
    }


    线程创建函数:
    int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void * (*func)(void *), void *arg);
    参数func 表示代一个参数void *,返回值也为void *;
    对于void *arg,参数传入,在gcc 3.2.2条件下,以下面两种方式传入都可编译通过。
    int ssock;
    int TCPechod(int fd);
    1.pthread_create(&th, &ta, (void *(*)(void *))TCPechod, (void *)ssock);
    2.pthread_create(&th, &ta, (void *(*)(void *))&TCPechod, (void *)&ssock);




    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/9643/showart_49987.html


    pthread_create(&tid,&attr,&func,(void)arg)只能传递一个参数给func,要是要传一个以上的参数呢?请指教


    定义一个结构然后传这个结构 
    pthread_create时,能否向thread_function传递多个参数?


    CODE:
    typedef union {
       size_t arg_cnt;
       any_possible_arg_types;
    } arg_type;


    arg_type args[ARG_NUM + 1];
    args[0].arg_cnt = ARG_NUM;
    args[1].xxx = ...;


    pthread_create (..., ..., thread_function, &args[0]);
    进去了自己解析。。


    -------------------------


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

  • 相关阅读:
    bzoj 3196/tyvj p1730 二逼平衡树
    AW201 可见的点 (欧拉函数)
    P3912 素数个数
    P1029 最大公约数和最小公倍数问题
    P1835 素数密度
    P2563 [AHOI2001]质数和分解
    P1075 质因数分解
    AW199 余数之和
    AW198 反素数
    AW197 阶乘分解
  • 原文地址:https://www.cnblogs.com/roger0212/p/4436732.html
Copyright © 2011-2022 走看看