本文共 2393 字,大约阅读时间需要 7 分钟。
Linux多线程编程中的pthread库功能总结
目录
线程管理
pthread_create:创建线程
- 函数原型:int pthread_create(pthread_t * tidp, const pthread_attr_t * attr, void *(*start_routine)(void*));
- 功能描述:用于创建新的线程,执行指定的线程入口函数。
- 注意事项:线程入口函数需采用特定的函数类型声明方式(如void *函数返回值)。
pthread_exit:线程退出
- 函数原型:void pthread_exit(void *exit_code);
- 功能描述:用于线程主函数退出,返回值可选。
pthread_join:等待线程终止
- 函数原型:int pthread_join(pthread_t thread, void **retval);
- 功能描述:等待指定线程终止,并可获得线程返回值。
- 注意事项:需使用pthread_join函数而非传统的wait/notify机制。
pthread_cancel:取消线程
- 函数原型:int pthread_cancel(pthread_t thread);
- 功能描述:强制终止指定线程。
- 注意事项:使用前需确保线程存在且处于运行状态。
线程属性管理
pthread_attr_init:初始化线程属性
- 函数原型:int pthread_attr_init(pthread_attr_t *attr, const pthread_attr_t *original_attr);
- 功能描述:初始化线程属性结构体。
- 注意事项:需在使用前使用pthread_attr_destroy销毁属性结构体。
pthread_attr_set:设置线程属性
- 函数原型:int pthread_attr_set(pthread_attr_t *attr, const pthread_attr_t *value);
- 功能描述:设置线程属性中的各个属性位。
- 常用属性包括:线程是否为joinable、优先级、堆栈大小等。
pthread_attr_get:获取线程属性
- 函数原型:int pthread_attr_get(pthread_attr_t *attr, const pthread_attr_t *value, size_t *offset);
- 功能描述:获取线程属性结构体的特定属性值。
- 注意事项:需要指定要获取的属性位(如PTHREAD_STACK_SIZE等)。
pthread_attr_destroy:销毁线程属性
- 函数原型:int pthread_attr_destroy(pthread_attr_t *attr);
- 功能描述:释放线程属性结构体的内存。
- 注意事项:必须在属性被初始化后使用。
线程间通信
pipe:管道通信
- 函数原型:int pipe(int *fd);
- 功能描述:创建一个双向通信通道。
- 常用场景:进程间通信。
semaphore:信号量
- 函数原型:int semanator_init(int *sem, int *ptrval, int nsems, int *id);
- 功能描述:初始化信号量。
- 常用函数:sem_wait、sem_signal等。
message队列:消息队列
- 函数原型:int msgget(char * pathname, int *type, int id);
- 功能描述:获取消息队列的描述符。
- 常用函数:msgrcv、msgsnd等。
shared memory:共享内存
- 函数原型:int shm_open(const char *name, int *shmid, int *region);
- 功能描述:打开共享内存区域。
- 常用函数:shmat、shmctl等。
线程间同步
pthread_mutex:互斥锁
- 函数原型:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_t *old);
- 功能描述:初始化互斥锁结构体。
- 常用函数:pthread_mutex_lock、pthread_mutex_unlock。
pthread_rwlock:读写锁
- 函数原型:int pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlock_t *old);
- 功能描述:初始化读写锁结构体。
- 常用函数:pthread_rwlock_rdlock、pthread_rwlock_wrlck、pthread_rwlock_unlock。
pthread_spin:自旋锁
- 函数原型:int pthread_spin_init(pthread_spin_t *lock, const pthread_spin_t *old);
- 功能描述:初始化自旋锁结构体。
- 常用函数:pthread_spin_lock、pthread_spin_unlock。
线程调度与优先级
pthread_sched:调度
- 函数原型:int pthread_sched(pthread_t thread, int policy, unsigned long *param);
- 功能描述:改变线程的调度策略和参数。
- 常用策略包括:PTHREAD_SCHED_OTHER、PTHREAD_SCHED_FIFO等。
pthread_priority:优先级设置
- 函数原型:int pthread_setpriority(pthread_t thread, int priority);
- 功能描述:设置线程的调度优先级。
- 注意事项:优先级范围受系统限制。
转载地址:http://vibyz.baihongyu.com/