概念:線程是共用進程地址空間的多任務結構
建立線程的相關函數:
1. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
參數1 :線程ID指標
參數2 :線程屬性,使用時通常為NULL
參數3 :線程函數指標
參數4 :線程函數入參
傳回值:0 成功,-1 失敗
標頭檔: #include <pthread.h>
2. int pthread_join(pthread_t thread, void **retval);
參數1:等待退出的線程ID
參數2:線程的結束資訊,通常為NULL,不為NULL時注意參數為void, 需要與pthread_exit配合使用。
傳回值:0 成功,-1 失敗
標頭檔: #include <pthread.h>
3.int pthread_mutex_init(pthread_mutex_t *mutex,
pthread_mutexattr_t *attr)
功 能:初始化鎖
參數1:初始化的鎖
參數2:鎖屬性,使用時通常為空白,使用預設屬性
傳回值:0 成功,-1 失敗
標頭檔: #include <pthread.h>
4.int pthread_mutex_lock(pthread_mutex_t *mutex)
功能:加鎖
參數1:鎖
傳回值:0 成功, -1 失敗
標頭檔: #include <pthread.h>
5.int pthread_mutex_unlock(pthread_mutex_t *mutex)
功能:解鎖
參數1:鎖
傳回值:0 成功, -1 失敗
標頭檔:#include <pthread.h>
6.int sem_init(sem_t *sem, int pshared, unsigned int value);
功能:初始化號誌
參數1:被初始化的號誌
參數2:使用範圍,0線程範圍內使用, 1進程範圍內使用
參數3:號誌持有資源個數
傳回值:0 成功, -1失敗
標頭檔:#include <semaphore.h>
7. int sem_wait(sem_t *sem)
功能:申請資源,申請成功後號誌的資源個數減1,當資源個數為0時阻塞
參數1:號誌指標
傳回值:0 成功, -1失敗
標頭檔:#include <semaphore.h>
8.int sem_post(sem_t *sem)
功能:釋放資源,釋放成功後號誌的資源個數加1,釋放資源後喚醒等待的線程
參數1:號誌指標
傳回值:0 成功, -1失敗
標頭檔:#include <semaphore.h>
訊號量:就是一種資源,定義訊號量時需要指定此訊號持有資源的個數,為非負整數
p:申請資源,將訊號量持有資源個數減一
申請不到資源時等待。
v:釋放資源,將訊號量持有資源個數加一。