1 线程创建
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
2 线程终止
2.1 退出线程
#include <pthread.h>
void pthread_exit(void *retval);
2.2 等待指定线程结束
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
3 线程同步
3.1 互斥量
3.2 读写锁
3.3 条件变量
参考资料[4]P309指出,条件本身是由互斥量保护的,线程在改变条件状态前必须首先锁住互斥量。也即是说,互斥量必需和条件变量一起使用,这点可以由pthead_cond_wait()的参数说明:
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
由上述函数参数可见,必须同时使用pthread_cond_t(条件变量)和pthread_mutex_t(互斥锁)。
此外,《Qt QWaitCondition的应用》则介绍了Qt中是如何实现条件变量的:QWaitCondition必需和QMutex结合使用。
3.4 信号量
见参考资料[8][9]。
4 实例
通过数组实现了一个FIFO(《FIFO的数组实现方式》),使用读写锁进行数据读写同步。
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <unistd.h>
#define FIFO_LENGTH 10
static uint8_t fifo_buffer[ FIFO_LENGTH ];
static uint16_t front = 0;
static uint16_t rear = 0;
static void *write_thread( void* );
static void *read_thread( void* );
static pthread_rwlock_t q_lock;
int main(int argc, char*argv[])
{
pthread_t wr_th;
pthread_t rd_th;
pthread_rwlock_init( &q_lock, NULL);
pthread_create( &wr_th, NULL, write_thread, NULL );
pthread_create( &rd_th, NULL, read_thread, NULL );
pthread_join(wr_th, NULL);
pthread_rwlock_destroy( &q_lock );
return 0;
}
void *write_thread( void*arg )
{
int i;
for( i = 0; i < 1000; i++) {
pthread_rwlock_wrlock( &q_lock );
fifo_buffer[ rear ] = i;
rear = ( rear + 1 ) % FIFO_LENGTH;
// queue full
if ( ( rear + 1 ) % FIFO_LENGTH == front )
front = (front + 1) % FIFO_LENGTH;
pthread_rwlock_unlock( &q_lock );
sleep( 1 );
}
return (void*)0;
}
void *read_thread( void*arg )
{
while( 1 ) {
// queue empty
pthread_rwlock_wrlock( &q_lock );
if ( front == rear ) {
pthread_rwlock_unlock( &q_lock );
//usleep( 1000 );
continue;
}
printf("%d\n", fifo_buffer[ front ]);
front = ( front + 1 ) % FIFO_LENGTH;
pthread_rwlock_unlock( &q_lock );
}
return (void*)0;
}
参考资料
[1]在Linux中使用线程
[2]linux多线程设计
[3]Linux--线程编程
[4]UNIX环境高级编程,第2版
[7]线程的创建及终止