创建线程:
int
pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)( void *), void *restrict arg);
const pthread_attr_t *restrict attr,
void *(*start_routine)( void *), void *restrict arg);
参数:
thread
输出线程id
attr
线程属性, 默认NULL
start_routine
线程执行函数
arg
线程执行参数
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
退出线程:
int
pthread_exit(
void
* value_ptr);
参数:
value_ptr
线程返回值指针
note: ptrhead_exit()退出调用此函数的线程并释放该线程占用的资源
头文件 pthread.h
库文件 pthread
等待指定线程结束:
int
pthread_join(pthread_t thread,
void
**value_ptr);
参数:
thread
一个有效的线程id
value_ptr
接收线程返回值的指针
note:调用此函数的线程在指定的线程退出前将处于挂起状态或出现错误而直接返回
如果value_ptr非NULL则value_ptr指向线程返回值的指针
函数成功后指定的线程使用的资源将被释放
头文件 pthread.h
库文件 pthread
获取当前线程id:
pthread_t pthread_self(
void
);
参数:
note:返回当前函数的id
头文件 pthread.h
库文件 pthread
互斥:
说到多线程,最关心的就是数据访问
/
改变的同步问题。
windows
下有临界区和信号事件等手段来防止多个线程同时读
/
写同一个数据,那么
linux
呢?
多线程变成时多使用互斥
pthread_mutex_t
来起到防止同时访问或改变同一数据
.
创建互斥:
int
pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
const pthread_mutexattr_t *restrict attr);
参数:
mutex
输出互斥id
attr
互斥属性, 默认NULL
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
锁住互斥:
int
pthread_mutex_lock(pthread_mutex_t *mutex);
参数:
mutex
互斥id
note:如果指定的互斥id已经被锁住那么呼叫线程在互斥id完全解锁前将
一直处于挂起状态,否则将锁住互斥体
头文件 pthread.h
库文件 pthread
int
pthread_mutex_trylock(pthread_mutex_t *mutex);
参数:
mutex
互斥id
note:如果指定的互斥id已经被锁住那么将直接返回一个错误,通过判断
此错误来进行不同的处理
头文件 pthread.h
库文件 pthread
解锁互斥:
int
pthread_mutex_unlock(pthread_mutex_t *mutex);
参数:
mutex
互斥id
note:如果指定的互斥id已经被锁住那么对其解锁
头文件 pthread.h
库文件 pthread
释放互斥:
int
pthread_mutex_destroy(pthread_mutex_t *mutex);
参数:
mutex
互斥id
note:释放指定的mutex占用的资源
头文件 pthread.h
库文件 pthread