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

    转自:http://blog.csdn.net/yeyuangen/article/details/6757525

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

  • 相关阅读:
    什么是主从复制、读写分离、为什么要使用
    Swift 4.0 + Ipad开发项目中值得注意知识点
    Swift细节记录<一>
    ECMAScript 6复习<一>
    Swift4.0复习访问控制与作用域
    Swift4.0复习操作符方法与操作符的定制
    Swift4.0复习错误处理
    Swift4.0复习扩展
    Swift4.0复习泛型
    TCP的三次握手(建立连接)和四次挥手(关闭连接)
  • 原文地址:https://www.cnblogs.com/x_wukong/p/5675748.html
Copyright © 2011-2022 走看看