[TOC]
线程的创建与运行
#include
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相当于线程main函数的、在单独执行流中执行的函数地址值(函数指针)
- arg通过第三个参数传递调用函数时的 包含传递参数信息的变量 的地址
- 成功0,失败返回其他值
int pthread_join(pthread_t thread, void** status);
- thread该ID的线程终止后,此函数才会返回
- status保存线程的main函数返回值的指针变量地址值
线程同步
线程安全的函数
指函数在被多个线程同时调用也不会引发问题
_t后缀的函数通常为线程安全函数,如:gethostbyname和gethostbyname_t
通过定义宏来将gethostbyname改为gethostbyname_r:gcc -D_REENTRANT mythread.c -lpthread
互斥量
Mutual Exclusion
也即锁机制
#include
int pthread_mutex_init(pthread_mutex_t* mutex,const pthread_mutexattr_t* attr)
int pthread_mutex_destroy(pthread_mutex_t* mutex)
- mutex保存互斥量的变量的地址值
- attr互斥量属性,没有需要特别指定时传递NULL
- 使用时需要声明pthread_mutex_t mutex;
- 成功 0,失败 其他值
int pthread_mutex_lock(pthread_mutex_t* mutex)
int pthread_mutex_unlock(pthread_mutex_t* mutex);
成功 0,失败 其他值
信号量
#include
int sem_init(sem_t* sem, int pshared, unsigned int value);
int sem_destroy(sem_t* sem);
- sem保存信号量的变量的地址值
- pshared可由多少个进程共享;0时只允许1个进程内部使用
- value指定新创建的信号量初始值
int sem_post(sem_t* sem);
int sem_wait(sem_t* sem);
线程的销毁与多线程并发客户端的实现
销毁方法
Linux线程并不是在首次调用的线程main函数返回时自动销毁
pthread_join:调用时,线程终止前,调用该函数的线程会进入阻塞状态 pthread_detach:调用该函数不会引起线程终止或阻塞,调用后会销毁已终止的线程