自学pthread

man -k pthread  查看所有命令以及命令描述 man指的是menu

man pthread_create 创建线程

apt-get install manpages-posix-dev

/usr/sbin 是安装目录

usleep()是微秒

sleep()是秒

gcc 01.c -o 01 -lpthread

运行  ./01

线程是进程下的单元
线程的使用
pthread_create 创建线程
pthread_join 等待线程结束
pthread_exit 退出线程 自杀
pthread_cancle 他杀

互斥锁
pthread_mutex_init         初始化锁
pthread_mutex_lock       加锁
pthread_mutex_unlock   解锁
pthread_mutex_destroy  销毁互斥锁

条件变量
pthread_cond_init   初始化
pthread_cond_signal  发通知
pthread_cond_wait     等待产品
pthread_cond_destroy  销毁

代码示例:
01.c
#include 
#include 
#include 
#include 

void* thr_fun(void* arg){
	char* no = (char*)arg;
	int i= 0;
	for(; i < 10; i++){
	printf("%s thread, i:%d\n",no,i);	
		if(i==5){
		//线程退出
		pthread_exit(2);
		//他杀 pthread_cancel
		}	
	}
	return 1;
}

void main(){
	printf("main thread\n");
	//线程id
	pthread_t tid;
	//线程的属性,NULL默认属性
	//thr_fun,线程创建之后执行的函数
	pthread_create(&tid,NULL,thr_fun,"1");
	void* rval;
	//等待tid线程结束
	//thr_fun与退出时传入的参数,都作为第二个参数内容
	pthread_join(tid,&rval);
	printf("rval:%d\n",(int)rval);
}
02.c
#include                                                          
#include 
#include 
#include 

int i = 0;
//互斥锁
pthread_mutex_t mutex;

void* thr_fun(void* arg){
	//加锁
	pthread_mutex_lock(&mutex);
	char* no = (char*)arg;
	for(;i < 5 ; i++){
	printf("%s thread, i:%d\n",no,i);
	//sleep是秒 unsleep是微秒
	sleep(1);
	}
	i=0;
	//解锁
	pthread_mutex_unlock(&mutex);
}

void main(){
	pthread_t tid1,tid2;
	//初始化互斥锁
	pthread_mutex_init(&mutex,NULL);
	
	pthread_create(&tid1,NULL,thr_fun,"No1");
	pthread_create(&tid2,NULL,thr_fun,"No2");
	
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	//销毁互斥锁
	pthread_mutex_destroy(&mutex);
}
03.c(生产者和消费者关系)
#include 
#include 
#include 
#include 

//消费者数量
#define CONSUMER_NUM 2
//生产者数量
#define PRODUCER_NUM 1

pthread_t pids[CONSUMER_NUM+PRODUCER_NUM];

//产品队列
int ready = 0;

//互斥锁
pthread_mutex_t mutex;
//条件变量
pthread_cond_t has_product;

//生产
void* producer(void* arg){
	int no = (int)arg;
	//条件变量
	for(;;){
		pthread_mutex_lock(&mutex);
		//往队列中添加产品
		ready++;
		printf("producer %d, produce product\n",no);
		//fflush(NULL);
		//通知消费者,有新的产品可以消费了
		//会阻塞输出
		pthread_cond_signal(&has_product);
		printf("producer %d, singal\n",no);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

//消费者
void* consumer(void* arg){
	int num = (int)arg;
	for(;;){
		pthread_mutex_lock(&mutex);
		//while?
		//superious wake ‘惊群效应’
		while(ready==0){
			//没有产品,继续等待
			//1.阻塞等待has_product被唤醒
			//2.释放互斥锁,pthread_mutex_unlock
			//3.被唤醒时,解除阻塞,重新申请获得互斥锁pthread_mutex_lock
			printf("%d consumer wait\n",num);
			pthread_cond_wait(&has_product,&mutex);
		}
		//有产品,消费产品
		ready--;
		printf("%d consume product\n",num);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}

void main(){
	//初始化互斥锁和条件变量                                                
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&has_product,NULL);
	printf("init\n");

	int i;
	for(i=0; i


你可能感兴趣的:(Android)