🤖 AI文章摘要 qwen-turbo-latest
加载中...

1. pthread.h

1.1 数据结构

  早期的linux并没有设计线程的概念, 线程概念是到后来借鉴windows才引入的. linux的线程与和进程底层都是使用clone()函数创建的, 但线程具有高并发\低占用\通信方便的优点

  • 使用多线程尽量避免使用信号, 多线程对信号支持不好
  • 多线程时, 线程的errno每个线程独立
  • 多线程时, 若主线程return则进程退出, 其他线程也会退出. 主线程return前使用pthread_exit()-
  • 查看线程库版本getconf GNU_LIBPTHREAD_VERSION

1.2 函数

  // 线程的创建与销毁
int pthread_create(
	pthread_t *restrict thread, 			//线程id结构体指针
	const pthread_attr_t *restrict attr, 	//设置线程属性,NULL表示不指定属性. 若需要指定属性则可以创建该结构体, 并使用pthread_attr_init()初始化, pthread_attr_destroy销毁, 可以掌握setdetachstate()进行创建时分离
	void *(*start_routine)(void *), 		//设置线程执行函数, 注意线程执行函数的参数固定为void*
	void *restrict arg)						//设置线程执行函数的参数, 注意该参数应该线程唯一, 否则会发生线程安全问题.

int pthread_join(		//回收线程资源, 和wait比较类似它是阻塞的
	pthread_t thread, 	//传出的thread参数
	void retval): 		//注意线程函数的返回值是一个指针, 这里传一个二级指针用于将线程返回参数传出

int pthread_detach(pthread_t thread)				//线程分离, 分离后的线程不需要要join回收. 调用join报错
int pthread_cancel(pthread_t thread)				//杀死线程
int pthread_equal(pthreadd_t t1 , pthreadd_t t2 )	//比较两个线程的
void pthread_exit(void *retval)						//退出线程, 该函数不会返回
  
  //互斥量
int pthread_mutex_init(								//初始锁(互斥量),互斥量在任意时刻只能由一个线程获取. 简便方式: pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;可以这样初始化
	pthread_mutex_t *restrict mutex, 				//
	const pthread_mutexattr_t *restrict attr);  
int pthread_mutex_lock(pthread_mutex_t *mutex)		//已经加锁的阻塞等待  
int pthread_mutex_trylock(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 rwlock = PTHREAD_RWLOCK_INITIALIZER
	pthread_rwlock_t *restrict rwlock, 				//
	const pthread_rwlockattr_t *restrict attr)		//
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)	

//条件变量
int pthread_cond_init(							// 初始化条件变量, 注意条件变量不是锁, 简便书写形式 pthread_cond_t cond = PTHREAD_COND_INITIALIZE
	pthread_cond_t *restrict cond, 				//
	const pthread_condattr_t *restrict attr)	//
int pthread_cond_wait(							//调用该时, 需要先获得锁, 若获得锁后未满足条件则自动释放锁, 并阻塞在该函数中, 注意条件变量不是锁, 调用该函数需要一个锁变量
	pthread_cond_t *restrict cond, 				//
	pthread_mutex_t *restrict mutex)			//
int pthread_cond_signal(pthread_cond_t *cond)	//释放信号, 调用该函数时会唤醒一个被条件变量阻塞的线程
int pthread_cond_destroy(pthread_cond_t *cond)	//
  

2. semaphore.h

信号量

2.1 数据结构

2.2 函数

  int sem_init(				//
	sem_t *sem, 			//
	int pshared, 			//
	unsigned int value): 	//
int sem_wait(sem_t *sem)	//
int sem_post(sem_t *)		//
int sem_destroy(sem_t *sem)	//