线程创建与同步(互斥锁,自旋锁,读写锁,条件变量)

线程创建与销毁

pthread_create()创建线程
pthread_self()获取当前线程自身的ID
pthread_equal()比较两个线程ID
pthread_join()一个线程等待另一个线程结束,通常结合pthread_create()一起使用
pthread_exit()线程退出

线程同步

互斥与自旋:
互斥特点:
	等时时间片让给其他线程。
自旋特点:
	最多只能被一个可执行线程持有。
	等时自旋等待。
	适用:保持锁时间短的情况
	
读写锁:
	读时,可读不可写。写时,不可读不可写。
	适用对数据结构进行读的次数比写的次数多的情
况。
	自旋等待。

互斥锁

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
//初始化锁
int pthread_mutex_lock(pthread_mutex_t *mutex);//阻塞加锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);//解锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);//销毁互斥锁

读写锁

读写锁初始化和销毁
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict 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);

自旋锁

spin_lock(&mr_lock);
spin_unlock(&mr_lock);

条件变量

等待“条件变量的条件成立”而阻塞
intpthread_cond_wait(pthread_cond_t*cond, pthread_mutex_t*mutex);
另一个线程使"条件成立"
intpthread_cond_signal(pthread_cond_t*cond);

调用方法:

#include   
#include   
#include 


ret_thrd1=pthread_create(&thread1,NULL,(void *)&print_message_function,(void *)message1);
tmp1=pthread_join(thread1,&retval);
pthread_exit("success");

信号量:
sem_t sem;
res = sem_init(&sem, 0, 0);	//初始化为0
sem_wait(&sem);		//--
sem_post(&sem);  	//++
sem_destroy(&sem); 

互斥量:
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex)
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);

自旋锁:
spinlock_t spinlock;
int spin_init(&spinlock,);
int spin_lock(&spinlock);
//int pthread_spin_trylock(&spinlock);
int unlock(&spinlock);
int destroy(&spinlock);

读写锁:
pthread_rwlock_t rwlock;
pthread_rwlock_init(&rwlock,NULL);
pthread_rwlock_wrlock(&rwlock);
pthread_rwlock_rdlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_destroy(&rwlock);

你可能感兴趣的:(进程与线程)