Linux 下C语言多线程编程

进程与线程的区别

进程拥有独立的地址空间,而且进程间的数据空间也相互独立,数据的传递得通过通信的方式;

线程是在一个进程下同时运行,多个线程之间的数据共享

线程的启动

函数原型:

/* Create a new thread, starting with execution of START-ROUTINE
   getting passed ARG.  Creation attributed come from ATTR.  The new
   handle is stored in *NEWTHREAD.  */
extern int pthread_create (pthread_t *__restrict __newthread,
			   const pthread_attr_t *__restrict __attr,
			   void *(*__start_routine) (void *),
			   void *__restrict __arg) __THROWNL __nonnull ((1, 3));

第一个参数为指向线程标识符的指针;
第二个参数为线程的属性;
第三个参数是线程运行函数的起始地址;
第四个参数是运行函数的参数;
z注:返回0表示创建成功,非o创建失败;EAGAIN表示系统不允许创建(线程数量过多),EINVAL 第二个参数的属性非法

线程的退出

1 线程函数执行完返回

2 调用pthread_exit结束

相关函数

pthread_join函数

/* Make calling thread wait for termination of the thread TH.  The
   exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
   is not NULL.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int pthread_join (pthread_t __th, void **__thread_return);

第一个参数为等待的线程的标识符

第二个参数为用户定义的指针,它可以用来存储被等待线程的返回值

:这个函数是一个线程阻塞函数,调用它将会一直等着被等带的线程函数执行完返回

pthread_detach函数

/* Indicate that the thread TH is never to be joined with PTHREAD_JOIN.
   The resources of TH will therefore be freed immediately when it
   terminates, instead of waiting for another thread to perform PTHREAD_JOIN
   on it.  */
extern int pthread_detach (pthread_t __th) __THROW;

参数就是线程的标识符,一旦调用该函数,该线程就不能再调用pthread_join加入等待列表,线程函数执行完以后会立即释放资源,使用此函数时一般不关心执行结果。

pthread_exit函数

/* Terminate calling thread.

   The registered cleanup handlers are called via exception handling
   so we cannot mark this function with __THROW.*/
extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__));

参数是函数的返回值,只要pthread_join的第二个参数不是NULL,这个值将被传递给__thread_return

:一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线程返回错误,错误代码:ESRCH

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值