linux多线程编程(四)

2019-10-14 12:57:31王冬梅

linux线程分为两类:一是核心级支持线程,二是用户级的线程。一般都为用户级的线程。

一、多线程的几个常见函数

要创建多线程必须加载pthread.h文件,库文件pthread。线程的标识符pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:typedef  unsigned  long  int  pthread_t

1.创建线程:

int pthread_create(pthread_t *restrict thread,
           const pthread_attr_t *restrict attr,
           void *(*start_routine)(void*), void *restrict arg);
参数:
      thread输出线程id
     attr 线程属性, 默认NULL
      start_routine线程执行函数
      arg线程执行参数 
note:函数成功返回0 否则返回错误码

2.等待指定线程结束:

int pthread_join(pthread_t thread,void **value_ptr);
参数:
      thread一个有效的线程id
      value_ptr 接收线程返回值的指针
note:调用此函数的线程在指定的线程退出前将处于挂起状态或出现错误而直接返回,如果value_ptr非NULL则value_ptr指向线程返回值的指针,函数成功后指定的线程使用的资源将被释放。

3.退出线程:

int pthread_exit(void * value_ptr);
参数:
      value_ptr 线程返回值指针
note: ptrhead_exit()退出调用此函数的线程并释放该线程占用的资源。

4.获取当前线程id:

pthread_t pthread_self(void);
参数:     
note:返回当前函数的id

5.互斥

创建互斥:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
                     const pthread_mutexattr_t *restrict attr);
参数:
      mutex输出互斥id
     attr 互斥属性, 默认NULL
note:函数成功返回0 否则返回错误码
锁住互斥:
int pthread_mutex_lock(pthread_mutex_t *mutex);
参数:
      mutex互斥id
note:如果指定的互斥id已经被锁住那么呼叫线程在互斥id完全解锁前将一直处于挂起状态,否则将锁住互斥体。
int pthread_mutex_trylock(pthread_mutex_t *mutex);
参数:
      mutex互斥id
note:如果指定的互斥id已经被锁住那么将直接返回一个错误,通过判断此错误来进行不同的处理。pthread_mutex_trylock和pthread_mutex_lock相似,不同的是pthread_mutex_trylock只有在互斥被锁住的情况下才阻塞。