加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

UNIX环境高级编程:pthread_create的问题

发布时间:2016-10-03 06:35:27 所属栏目:Unix 来源:站长网
导读:副标题#e# linux 下常用的创建多线程函数pthread_create(pthread_t * thread , pthread_attr_t * attr , void *(*start_routine)(void*) , void *args); 其中第一个参数用来保存线程信息,第二个参数指新线程的运行属性,可以设置为NULL,第三个参数为自定
副标题[/!--empirenews.page--]

linux 下常用的创建多线程函数pthread_create(pthread_t * thread , pthread_attr_t * attr , void *(*start_routine)(void*) , void *args);

其中第一个参数用来保存线程信息,第二个参数指新线程的运行属性,可以设置为NULL,第三个参数为自定义的线程函数,第四个参数就是线程函数需要用到的参数,一般如果要传递多个参数,可以设置为结构体(struct)类型,这里我们使用int类型的变量。  

下面我着重讨论一个用for结构来创建多个线程时参数传递的问题:

#include <stdio.h>  
#include <stdlib.h>  
#include <pthread.h>  
      
      
#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;  
    printf("the id of this thread is %dn",t_id);  
    pthread_mutex_unlock(&mutex);      
    return (void*)NULL;  
}  
      
void init()  
{  
    pthread_mutex_init(&mutex, NULL);  
    int i;  
    for( i=0; i<th_pop; i++)  
    {  
        pthread_create(&a_thread[i] , NULL , thread_func , &i);  
    }  
    //wait the end of the threads;  
    for( i=0; i<th_pop; i++)  
    {  
        int res = pthread_join(a_thread[i] , NULL);  
        if(res != 0)  
            printf("the thread id: %d ends fail n",i);  
    }  
    pthread_mutex_destroy(&mutex);  
          
}  
      
int main()  
{  
    init();  
    return 0;  
}

运行结果:

huangcheng@ubuntu:~$ ./a.out
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

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读