Chinaunix首页 | 论坛 | 博客
  • 博客访问: 247088
  • 博文数量: 108
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 314
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-29 10:58
文章分类

全部博文(108)

文章存档

2015年(20)

2014年(88)

我的朋友

分类: 嵌入式

2014-04-03 08:57:05

创建线程函数:
int  pthread_create(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void*),void *arg);

    thread:新线程创建成功后,保存新线程的标识符
    attr:设置线程的属性,一般不需要什么特殊的属性,直接传NULL即可
    start_routine: 是个函数地址,线程启动后要执行的函数
    arg:传给线程启动函数的参数 


例子:
#include


#include

#include

#include

 

struct menber

{

    int a;

    char *s;

};

 

/*线程执行函数*/

void *create(void *arg)

{

    struct menber *temp;

    temp=(struct menber *)arg;

    printf("menber->a = %d  \n",temp->a);

    printf("menber->s = %s  \n",temp->s);

    return (void *)0;

}

 

int main(int argc,char *argv[])

{

    pthread_t tidp;

    int error;

    struct menber *b;

 

      /*为结构体指针b分配内存并赋值*/

    b=(struct menber *)malloc( sizeof(struct menber) );

    b->a = 4;

    b->s = "zieckey";

   

      /*创建线程并运行线程执行函数*/

    error = pthread_create(&tidp, NULL, create, (void *)b);

    if( error )

    {

        printf("phread is not created...\n");

        return -1;

    }

 

    sleep(1); //进程睡眠一秒使线程执行完后进程才会结束

 

    printf("pthread is created...\n");

    return 0;

}

 

 

编译时要加上编译参数 -lpthread
转载:http://blog.chinaunix.net/uid-24219701-id-67589.html

阅读(940) | 评论(0) | 转发(0) |
0

上一篇: 复制构造函数简单应用

下一篇:线程终止

给主人留下些什么吧!~~