您的位置:首页 > 运维架构 > Linux

Linux多线程编程及线程同步方法总结

2015-07-12 14:59 561 查看
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版

[5]Linux 线程(创建/等待/终止)

[6]linux下多线程的创建与等待详解

[7]线程的创建及终止

[8]最全面的linux信号量解析

[9]秒杀多线程第八篇 经典线程同步 信号量Semaphore
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: