第11章线程总结
1 线程标识
pthread_t类型
int pthread_equal(pthread_t tid1,pthread_t tid2) pthread_t pthread_self()
2 创建线程
int pthread_create(pthread_t *tid,pthread_attr_t *attr,void *(*start_rtn)(void *),void *arg)
tid保存线程id,attr描述线程属性,start_rtn为线程起始函数(参数和返回值都是void *),arg是传递给起始函数的参数
新创建线程和调用线程的执行顺序是不确定的,新创建线程继承调用线程的信号屏蔽字,但是清除未决信号
3 终止线程
三种方式:
1)从启动例程返回 return
2)被其他线程取消pthread_cancel
int pthread_cancel(pthread_t tid)
3)调用pthread_exit
void pthread_exit(void *rval)
rval可以被其他线程通过pthread_join捕捉到:
int pthread_join(pthread_t tid,void **rval)
调用线程将等待tid线程终止,并试图获取其返回码(终止码)
清理函数:
void pthread_cleanup_push(void (*rtn)(void *),void *arg) void pthread_cleanup_pop(int execute)
4 线程同步
1)互斥量
互斥量:pthread_mutex_t int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *attr) int pthread_mutex_destroy(pthread_mutex_t *mutex) int pthread_mutex_lock(pthread_mutex_t *mutex) int pthread_mutex_unlock(pthread_mutex_t *mutex) int pthread_mutex_trylock(pthread_mutex_t *mutex)
2)读写锁
与互斥量的区别在于:多线程共享读锁,独占写锁
读写锁:pthread_rwlock_t int pthread_rwlock_init(pthread_rwlock_t *rwlock,pthread_rwlockattr_t *attr) int pthread_rwlock_destroy(pthread_rwlock_t *rwlock) int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock) int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock) int pthread_rwlock_unlock(pthread_rwlock_t *rwlock) int pthread_rwlock_tyrrdlock(pthread_rwlock_t *rwlock) int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)
3)条件变量
条件变量提供了线程会合的场所,允许线程以无竞争的方式等待某个条件的发生
条件变量受互斥量保护,获取互斥量的线程A可以调用pthread_cond_wait(&cond,&mutex)
A线程被放到条件变量的线程列表上,对互斥量解锁,进入休眠状态等待条件发生
其他线程获取互斥量,一定条件下调用pthread_cond_signal(&cond)或pthread_cond_broadcast(&cond)函数,然后释放互斥量
A线程pthread_cond_wait函数返回,并重新获取互斥量
条件变量:pthread_cond_t int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *attr) int pthread_cond_destroy(pthread_cond_t *cond) int pthread_cond_wait(ptherad_cond_t *cond,pthread_mutex_t *mutex) int pthread_cond_timedwait(pthread_cond_t *cond,pthread_mutex_t *mutex,struct timespec *timeout) int pthread_cond_signal(pthread_cond_t *cond) int pthread_cond_braodcase(pthread_cond_t *cond)
获取互斥量的线程通过调用pthread_cond_wait、pthread_cond_timedwait函数,将线程放到等待条件的线程列表上,释放互斥量并休眠等待
之后获取互斥量的线程可以在条件发生时调用pthread_cond_signal、pthread_cond_broadcast函数,当线程释放互斥量时,等待条件的线程列表上的线程可以从pthread_cond_wait函数返回并重新获取互斥量