pthread_create函数
函数简介
pthread_create是UNIX环境创建线程函数
头文件
#include<pthread.h>
函数声明
int pthread_create(pthread_t *thread, pthread_attr_t attr, void (*start_routine)(void *), void *arg);
返回值
若成功则返回0,否则返回出错编号
参数
第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
函数调用:
pthread_create函数调用时候,传入的第三参数(运行函数)会在内部执行。
另外
pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在线程函数在编译时,需要连接库函数
获取线程ID pthread_self():
#include <pthread.h>
pthread_t pthread_self(void);
pthread_t tid = pthread_self(); //获取线程自身id,以方便调试打印信息等
说明:
获取本线程自身的 ID。线程 ID 类型是 pthread_t ,这个类型一般为long long 型,8个字节。
2、pthread_join函数
函数pthread_join用来等待一个线程的结束。
函数原型为:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
参数:
第一个参数为被等待的线程标识符,
第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。(常设置null)
这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。
注意:
相关函数:
条件变量:
pthread_cond_wait()
pthread_cond_timedwait()
pthread_join()
pthread_cond_signal()
pthread_cond_broadcast()
锁操作:
pthread_mutex_destroy ()
pthread_mutex_lock()、
pthread_mutex_unlock()
pthread_mutex_trylock()
pthread_cond_wait() 用于阻塞当前线程,等待别的线程使用pthread_cond_signal()或pthread_cond_broadcast来唤醒它。 pthread_cond_wait() 必须与pthread_mutex