天天看点

pthread_create传递参数/单个或者多个

linux 下常用的创建多线程函数pthread_create(pthread_t * thread , pthread_attr_t * attr , void *(*start_routine)(void*) , void *args);其中第一个参数用来保存线程信息,第二个参数指新线程的运行属性,可以设置为NULL,第三个参数为自定义的线程函数,第四个参数就是线程函数需要用到的参数,一般如果要传递多个参数,可以设置为结构体(struct)类型,这里我们使用int类型的变量。 下面我着重讨论一个用for结构来创建多个线程时参数传递的问题

先看下面的例子,后面附有结果,先不要看,猜测一下会有什么样的输出:

#include<iostream>

#include<pthread.h>

#include<semaphore.h>

using namespace std;

#define th_pop 20 //

pthread_mutex_t mutex;

pthread_t a_thread[th_pop];

void * thread_func(void *args)

{

    pthread_mutex_lock(&mutex);

    int t_id = *(int*)args;

    cout<<"the id of this thread is "<<t_id<<endl;

    pthread_mutex_unlock(&mutex);    

    return (void*)NULL;

}

void init()

{

    pthread_mutex_init(&mutex, NULL);

    for(int i=0; i<th_pop; i++)

    {

        pthread_create(&a_thread[i] , NULL , thread_func , &i);

    }

    //wait the end of the threads;

    for(int i=0; i<th_pop; i++)

    {

        int res = pthread_join(a_thread[i] , NULL);

        if(res != 0)

            cout<<"the thread id: "<< i<<" ends fail"<<endl;

    }

    pthread_mutex_destroy(&mutex);

}

int main()

{

    init();

    return 0;

}

编译运行

g++ -fpermissive args.cc -o args.o -pthread

./args.o

下面是输出结果,由于线程执行的不确定性,可能你执行的时候得到的结果并非如此,这只是一个代表而已

the id of this thread is 2

the id of this thread is 8

the id of this thread is 9

the id of this thread is 9

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

the id of this thread is 20

看到这个结果有没有感觉到有什么不对呢?可能你会感觉到很纳闷,怎么出现了那么多的id=20的结果呢?其实这个认真分析一下并不难理解:

首先pthread_create函数传递的是一个指针型的参数,即传递的是一个地址而已,这样在执行for结构时

for(int i=0; i<th_pop; i++)

    {

        pthread_create(&a_thread[i] , NULL , thread_func , &i);

    }

该块快速执行完成,并且将i置为20,故而传递的地址指向的内容为20,同时其它的线程还没来得及执行              int t_id = *(int*)args;,这样就使得多个线程都指向同一个地址,内容为20,解决该问题的一个办法为中for结构中加入sleep(1),这样当sleep时间大于线程函数执行时间,就可以得到一个正确的结果,不过这种办法剥掉了并发性,并不可取,下面我们采用另一种方法。

我们只修改init()函数

void init()

{

    pthread_mutex_init(&mutex, NULL);

    int thread_id[th_pop];

    for(int i=0; i<th_pop; i++)

        thread_id[i] = i;

    for(int i=0; i<th_pop; i++)

    {

        int *t = thread_id +i;

        pthread_create(&a_thread[i] , NULL , thread_func , (void*)t);

    }

    //wait the end of the threads;

    for(int i=0; i<th_pop; i++)

    {

        int res = pthread_join(a_thread[i] , NULL);

        if(res != 0)

            cout<<"the thread id: "<< i<<" ends fail"<<endl;

    }

    pthread_mutex_destroy(&mutex);

}

下面输出结果

the id of this thread is 0

the id of this thread is 4

the id of this thread is 2

the id of this thread is 5

the id of this thread is 1

the id of this thread is 3

the id of this thread is 6

the id of this thread is 7

the id of this thread is 8

the id of this thread is 9

the id of this thread is 10

the id of this thread is 11

the id of this thread is 12

the id of this thread is 13

the id of this thread is 14

the id of this thread is 15

the id of this thread is 16

the id of this thread is 17

the id of this thread is 18

the id of this thread is 19

从这个例子中我们应该明白,要避免直接在传递的参数中传递发生改变的量,否则会导致结果不可测

http://hi.baidu.com/passionqiangli/blog/item/626ebe1ff8f103f5ae513319.html

===========================================================================

http://zhidao.baidu.com/question/315398992.html

涉及多参数传递给线程的,都需要使用结构体将参数封装后,将结构体指针传给线程

定义一个结构体

struct mypara

{

       var para1;//参数1

       var para2;//参数2

}

将这个结构体指针,作为void *形参的实际参数传递

struct mypara pstru;

pthread_create(&ntid, NULL, thr_fn,& (pstru));

函数中需要定义一个mypara类型的结构指针来引用这个参数 

void *thr_fn(void *arg)

{

       mypara *pstru;

       pstru = (* struct mypara) arg;

       pstru->para1;//参数1

       pstru->para2;//参数2

}

pthread_create函数接受的参数只有一个void *型的指针,这就意味着你只能通过结构体封装超过一个以上的参数作为一个整体传递。这是pthread_create函数的接口限定的,别人已经明确表明我只接受一个参数,你硬要塞给他两个肯定会出错了。所以通过结构体这种组合结构变通一下,同样实现了只通过一个参数传递,但通过结构指针对结构数据成员的引用实现多参数的传递

这种用结构体封装多参数的用法不仅仅用在pthread_create函数中,如果你自己设计的函数需要的参数很多〉=5个以上,都可以考虑使用结构体封装,这样对外你的接口很简洁清晰,你的函数的消费者使用起来也很方便,只需要对结构体各个成员赋值即可,避免了参数很多时漏传、误传(参数串位)的问题

结构体内包含结构体完全没有问题,很多应用都这么使用

举例如下:

http://wenku.baidu.com/view/48a302ed6294dd88d0d26b73.html

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. #include<pthread.h>  
  4. #include<errno.h>  
  5. #include<unistd.h>  
  6. typedef void* (*fun)(void*);    
  7. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  
  8. static pthread_cond_t recv_over = PTHREAD_COND_INITIALIZER;  
  9. static pthread_cond_t decode_over = PTHREAD_COND_INITIALIZER;  
  10. static pthread_cond_t play_over = PTHREAD_COND_INITIALIZER;  
  11. void* receive(void*);  
  12. void* decode(void*);  
  13. void* play(void*);  
  14. pthread_t tdec, tplay, trecv;  
  15. struct mypara   
  16. {   
  17.     int thread_id;  
  18.     char *thread_name;   
  19. };  
  20. int main(int argc, char** argv)  
  21. {  
  22.     struct mypara para;  
  23.     para.thread_id = 1;  
  24.     para.thread_name = "recv";  
  25.     int t1 = 0, t2 = 0, t3 = 0;  
  26.     t1 = pthread_create(&trecv, NULL, receive,& (para));  
  27.     if(t1 != 0)  
  28.         printf("Create thread receive error!\n");  
  29.     t2 = pthread_create(&tdec, NULL, decode, NULL);  
  30.     if(t2 != 0)  
  31.         printf("Create thread decode error!\n");  
  32.     t3 = pthread_create(&tplay, NULL, play, NULL);  
  33.     if(t3 != 0)  
  34.         printf("Create thread play error!\n");  
  35.     pthread_join(trecv, NULL);  
  36.     pthread_join(tdec, NULL);  
  37.     pthread_join(tplay, NULL);  
  38.     printf("leave main\n");  
  39.     exit(0);      
  40. }  
  41. void* receive(void* arg)  
  42. {  
  43.     printf("Start receive\n");  
  44.     int i = 0;  
  45.     char *s = NULL;  
  46.     struct mypara *recv_para;  
  47.     recv_para = (struct mypara *)arg;  
  48.     i = (*recv_para).thread_id;  
  49.     s = (*recv_para).thread_name;  
  50.     printf("NO : %d Name : %s\n",i,s);  
  51.     sleep(2);  
  52.     pthread_mutex_lock(&mutex);  
  53.     while (1)  
  54.     {  
  55.         printf("Receiving...\n");  
  56.         sleep(1);  
  57.         pthread_cond_signal(&recv_over);  
  58.         pthread_cond_wait(&decode_over, &mutex);   
  59.     }  
  60.     printf("End receive\n");  
  61.     pthread_exit(0);  
  62. }  
  63. void* decode(void* arg)  
  64. {  
  65.     printf("Start decode\n");  
  66.     while (1)  
  67.     {  
  68.         pthread_cond_wait(&recv_over, &mutex);   
  69.         printf("Decoding...\n");  
  70.         sleep(1);  
  71.         pthread_cond_broadcast(&decode_over);   //inform player ready to play  
  72.     }  
  73.     printf("End decode\n");  
  74.     pthread_exit(0);  
  75. }  
  76. void* play(void* arg)  
  77. {  
  78.     int ret;  
  79.     printf("Start play\n");  
  80.     while(1)  
  81.     {  
  82.         pthread_cond_wait(&decode_over, &mutex); //wait the signal from decoder  
  83.         printf("Playing...\n");  
  84.         sleep(1);  
  85.     }  
  86.     pthread_mutex_unlock(&mutex);  
  87.     printf("End play\n");  
  88.     pthread_exit(0);  
  89. }