创建线程:pthread_creat() 函数介绍

创建线程:pthread_creat() 函数介绍

语法

int pthread_creat(pthread_t *thread,
                  const pthread_attr_t *attr,
                  void *(*thread_routine)(void *),
                  void *arg)

参数介绍

pthread_t thread : pthread_t 表示线程的数据类型,实际上是void * 类型。 每一个pthread_t 的变量都可以表示一个线程。

const pthread_attr attr:* 手动设置线程的属性,比如线程调用策略,所用栈内存大小等。

thread_routine: 设置开启线程之后线程需要执行的函数。 可以只有一个参数或者没有。返回值和形参都是void*类型。

*arg: 指传递给thread_routine() 函数的实参,如果thread_routine 不需要任何参数是,arg设置为NULL.

返回值介绍: 如果pthread_creat() 函数成功创建线程时,返回数字0, 否则返回非0值。具体如下:

EAGAIN: 系统资源不足,无法提供创建线程所需的资源。

EINVAL: 传递的attr 参数无效。

举例说明

#include <stdio.h>
#include <pthread.h>  //pthread_creat() 需要该头文件
#include <unistd.h>	  //sleep() 函数需要该头文件


void *  _ThreadFuncLoop(void * arg)
{
	if(arg==NULL)
       	printf("arg is null \n");
    else
        printf("function:%s arg=%s\n",__FUNCTION__,(char*)arg);
}

int main()
{
   pthread_t threadT1,threadT2; 
   char *threadPra="only for test \n";
   int res=0;
    
   /*-------cread thread1 test---------*/
   printf("will test thread1 in function:%s,line:%d\n",__FUNCTION__,__LINE__);
   res=pthread_creat(&threadT1,NULL,_ThreadFuncLoop,NULL);
   if(res!=0)
   {
       printf("cread thread1 error!\n");
       return -1;
   }
   sleep(10);	//only for wait child thread.
    
   /*-------cread thread2 test---------*/
   printf("will test thread2 in function:%s,line:%d\n",__FUNCTION__,__LINE__);
   res=pthread_creat(&threadT2,NULL,_ThreadFuncLoop,(void*)threadPra);
   if(res!=0)
   {
       printf("cread thread2 error!\n");
       return -1;
   }
   sleep(20);
    
   return 1;
}

其它说明:

  • pthread_creat() 函数定义在pthread.h 中
  • pthread_creat() 创建成功之后,创建的新的子线程会立马执行用户设定的thread_routine() 函数。
  • pthread_attr 属性一般不设置,使用默认配置。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值