LV.5 进程、线程和进程间通信(4) - 线程的取消和互斥

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

目录

前言

1.线程的取消:

1.2如果没有取消点,手动设置一个

1.3设置取消使能或禁止

1.4设置取消类型

2.线程的清理

3.线程的互斥和同步

3.1临界资源:

3.2临界区

3.3互斥机制

3.4互斥锁的创建和销毁

3.4.1 互斥锁的创建

3.4.2 锁的销毁:

3.4.3 申请锁

3.4.4 释放锁

3.5读写锁

3.5.1读写锁的类型

3.6死锁

总结



前言


1.线程的取消:

意义:随时杀掉一个线程

int pthread_cancel(pthread_t thread);

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void* threadtest(void*arg){

printf("child thread\n");
//printf("线程 %d\n",(int)arg);
while(1){
sleep(2);
}
pthread_exit("hha...");
}

int main(int argc, const char *argv[])
{
	int ret;
	pthread_t ptd;
	void* hhh;
	ret = pthread_create (&ptd,NULL,threadtest,NULL);
	sleep(20);
	pthread_cancel(ptd);//取消线程
	pthread_join(ptd,&hhh);
	while(1){
	sleep(2);
	}
	return 0;
}

注意:线程的取消要有取消点才可以,不是说取消就取消,线程的取消点主要是阻塞的系统调用

运行段错误调试:

可以使用gdb调试

使用gdb 运行代码,gdb  ./youapp

(gdb) run

等待出现Thread 1 "pcancel" received signal SIGSEGV, Segmentation fault.

输入命令bt(打印调用栈)

(gdb) bt

#0  0x00007ffff783ecd0 in vfprintf () from /lib/x86_64-linux-gnu/libc.so.6

#1  0x00007ffff78458a9 in printf () from /lib/x86_64-linux-gnu/libc.so.6

#2  0x00000000004007f9 in main () at pcancel.c:21

确定段错误位置是pcancel.c 21行

1.2如果没有取消点,手动设置一个

没有取消点就是没有调用中断系统,(sleep就是取消点)

void pthread_testcancel(void);

1.3设置取消使能或禁止

int pthread_setcancelstate(int state, int *oldstate);

PTHREAD_CANCEL_ENABLE

PTHREAD_CANCEL_DISABLE

下面的代码结果(这里使用的是sleep()):

如果设置了PTHREAD_CANCEL_DISABLE,则不能取消,继续执行子线程,直到执行到

PTHREAD_CANCEL_DISABLE,然后退出子线程;此时test01和test02都打印了。

反之,只打印test01就结束。

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void* threadtest(void*arg){

printf("child thread\n");
//printf("线程 %d\n",(int)arg);
//pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
//while(1)
{
	printf("test01\n");
	sleep(20);
	//pthread_testcancel();//设置取消点,sleep是阻塞也是取消点
	printf("test02\n");
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
	printf("test03\n");
    while(1){
	    sleep(1);
    }
    pthread_exit("hha...");
    }
}

int main(int argc, const char *argv[])
{
	int ret;
	pthread_t ptd;
	void* hhh;
	ret = pthread_create (&ptd,NULL,threadtest,NULL);
	sleep(3);
	pthread_cancel(ptd);//取消线程
	printf("over...\n");
	pthread_join(ptd,&hhh);
	while(1){
	sleep(2);
	}
	return 0;
}

1.4设置取消类型

int pthread_setcanceltype(int type, int *oldtype);

PTHREAD_CANCEL_DEFERRED                等到取消点才取消

PTHREAD_CANCEL_ASYNCHRONOUS           目标线程会立即取消

2.线程的清理

必要性: 当线程非正常终止,需要清理一些资源。

void pthread_cleanup_push(void (*routine) (void *), void *arg)

void pthread_cleanup_pop(int execute)

注意:必须成对使用,理论上这是一对宏定义

routine 函数被执行的条件:

  1. 被pthread_cancel取消掉。
  2. 执行pthread_exit
  3. 非0参数执行pthread_cleanup_pop()

注意:

1.必须成对使用,即使pthread_cleanup_pop不会被执行到也必须写上,否则编译

2.pthread_cleanup_pop()被执行且参数为0,pthread_cleanup_push回调函数routine不会被执行。

3 pthread_cleanup_push pthread_cleanup_pop可以写多对,routine执行顺序正好相反(栈的顺序)

4.线程内的return 可以结束线程,也可以给pthread_join返回值,但不能触发pthread_cleanup_push里面的回调函数,所以我们结束线程尽量使用pthread_exit退出线程。

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void cleanup(void*arg){
printf("cleanup,arg=%s\n",(char*)arg);
}
void cleanup2(void*arg){
printf("cleanup,arg=%s\n",(char*)arg);
}

void* threadtest(void*arg){
printf("child thread\n");
pthread_cleanup_push(cleanup,"abcd");
pthread_cleanup_push(cleanup2,"efg");
while(1){
	printf("sjsjsj\n");
	sleep(1);
	}
pthread_exit("hha...");
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
//pthread_exit("hha...");
}

int main(int argc, const char *argv[])
{
	int ret;
	pthread_t ptd;
	void* hhh;
	ret = pthread_create (&ptd,NULL,threadtest,NULL);
	sleep(1);
	pthread_cancel(ptd);//取消线程
	printf("over...\n");
	pthread_join(ptd,&hhh);//回收线程
	while(1){
	sleep(1);
	}
	return 0;
}

3.线程的互斥和同步

3.1临界资源:

 一次只允许一个任务(进程、线程)访问的共享资源

不能同时访问的资源,比如写文件,只能由一个线程写,同时写会写乱。

比如外设打印机,打印的时候只能由一个程序使用。

外设基本上都是不能共享的资源。

生活中比如卫生间,同一时间只能由一个人使用。

必要性: 临界资源不可以共享

3.2临界区

访问临界资源的代码

3.3互斥机制

mutex互斥锁
任务访问临界资源前申请锁,访问完后释放锁

man手册找不到 pthread_mutex_xxxxxxx (提示No manual entry for pthread_mutex_xxx)的解决方法:

apt-get install manpages-posix-dev

3.4互斥锁的创建和销毁

3.4.1 互斥锁的创建

两种方法创建互斥锁,静态方式动态方式

动态方式

int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);

其中mutexattr用于指定互斥锁属性,如果为NULL则使用缺省属性。

静态方式

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

3.4.2 锁的销毁:

int pthread_mutex_destroy(pthread_mutex_t *mutex)

在Linux中,互斥锁并不占用任何资源,因此LinuxThreads中的 pthread_mutex_destroy()除了检查锁状态以外(锁定状态则返回EBUSY)没有其他动作。

互斥锁的使用:

3.4.3 申请锁

int pthread_mutex_lock(pthread_mutex_t *mutex)

int pthread_mutex_trylock(pthread_mutex_t *mutex)

成功时返回0,失败时返回错误码
mutex  指向要初始化的互斥锁对象
pthread_mutex_lock 如果无法获得锁,任务阻塞
pthread_mutex_trylock 如果无法获得锁,返回EBUSY而不是挂起等待

3.4.4 释放锁

int pthread_mutex_unlock(pthread_mutex_t *mutex)

 成功时返回0,失败时返回错误码
 mutex  指向要初始化的互斥锁对象
 执行完临界区要及时释放锁

vim 设置代码全文格式化:gg=G

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
pthread_mutex_t lock01 = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;//临界资源

void* thread02(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("thread02 write\n");
	int i = 0;
	char abc[] = "yao zhuan da qian!!!\n";
	char c;
	while(1){
		pthread_mutex_lock(&lock01);
		while(i < strlen(abc)){
			c = abc[i];
			fputc(c,fp);
			i++;
			usleep(1);
		}
		pthread_mutex_unlock(&lock01);
		i = 0;//反复写
		usleep(1);
	}
	pthread_exit("hha2...");
}
void* thread01(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("thread01 write\n");
	int i = 0;
	char abc[] = "wo shi da shuai ge!\n";
	char c;
	while(1){
		pthread_mutex_lock(&lock01);
		while(i < strlen(abc)){
			c = abc[i];
			fputc(c,fp);
			i++;
			usleep(1);
		}
		pthread_mutex_unlock(&lock01);
		i = 0;//反复写
		usleep(1);
	}
	pthread_exit("hha1...");
}

int main(int argc, const char *argv[])
{
	int ret,ret2;
	pthread_t pid1,pid2;
	void* hhh;
	//打开文件
	fp = fopen("1.txt","a+");

	ret = pthread_create(&pid1,NULL,thread01,NULL);
	ret2 = pthread_create(&pid2,NULL,thread02,NULL);
	sleep(1);
    //子线程已经分离,系统负责回收
	//pthread_join(pid1,&hhh);//回收线程
	//pthread_join(pid2,&hhh);//回收线程
	while(1){
		sleep(1);
	}
	//关闭文件
	fclose(fp);
	return 0;
}

3.5读写锁

必要性:提高线程执行效率

特性:

写者:写者使用写锁,如果当前没有读者,也没有其他写者,写者立即获得写锁;否则写者将等待,直到没有读者和写者。

读者:读者使用读锁,如果当前没有写者,读者立即获得读锁;否则读者等待,直到没有写者。

注意:

同一时刻只有一个线程可以获得写锁,同一时刻可以有多个线程获得读锁。

读写锁出于写锁状态时,所有试图对读写锁加锁的线程,不管是读者试图加读锁,还是写者试图加写锁,都会被阻塞。

读写锁处于读锁状态时,有写者试图加写锁时,之后的其他线程的读锁请求会被阻塞,以避免写者长时间的不写锁

3.5.1读写锁的类型

初始化一个读写锁   pthread_rwlock_init
读锁定读写锁pthread_rwlock_rdlock
非阻塞读锁定pthread_rwlock_tryrdlock
写锁定读写锁 pthread_rwlock_wrlock
非阻塞写锁定pthread_rwlock_trywrlock
解锁读写锁 pthread_rwlock_unlock
释放读写锁  pthread_rwlock_destroy

读写锁代码演示:

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

pthread_rwlock_t rwlock;
FILE *fp;//临界资源

void* read_thread02(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("rd_thread02\n");
	char buf[32] = {0};
	while(1){
		//rewind(fp);//指针回到初始位置
		pthread_rwlock_rdlock(&rwlock);
		while(fgets(buf,32,fp) != NULL){
			printf("read_id=%d,%s\n",(int)arg,buf);
			usleep(1000);
		}
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
}
void* read_thread01(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("rd_thread01\n");
	char buf[32] = {0};
	while(1){
		//rewind(fp);//指针回到初始位置
		pthread_rwlock_rdlock(&rwlock);
		while(fgets(buf,32,fp) != NULL){
			printf("read_id=%d,%s\n",(int)arg,buf);
			usleep(1000);
		}
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
}
void* thread02(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("thread02 write\n");
	int i = 0;
	char abc[] = "yao zhuan da qian!!!\n";
	char c;
	while(1){
		pthread_rwlock_wrlock(&rwlock);
		while(i < strlen(abc)){
			c = abc[i];
			fputc(c,fp);
			i++;
			usleep(1);
		}
		pthread_rwlock_unlock(&rwlock);
		i = 0;//反复写
		usleep(1000);
	}
	pthread_exit("hha2...");
}
void* thread01(void*arg){
	pthread_detach(pthread_self());//子线程分离
	printf("thread01 write\n");
	int i = 0;
	char abc[] = "wo shi da shuai ge!\n";
	char c;
	while(1){
		pthread_rwlock_wrlock(&rwlock);
		while(i < strlen(abc)){
			c = abc[i];
			fputc(c,fp);
			i++;
			usleep(1);
		}
		pthread_rwlock_unlock(&rwlock);
		i = 0;//反复写
		usleep(1000);
	}
	pthread_exit("hha1...");
}

int main(int argc, const char *argv[])
{
	int ret,ret2,ret3,ret4;
	pthread_t pid1,pid2,read_pid1,read_pid2;
	void* hhh;
	int a =1,b = 2;
	//打开文件
	fp = fopen("1.txt","a+");
	pthread_rwlock_init(&rwlock,NULL);
	ret = pthread_create(&pid1,NULL,thread01,NULL);
	ret2 = pthread_create(&pid2,NULL,thread02,NULL);
	ret3 = pthread_create(&read_pid1,NULL,read_thread01,(void*)a);
	ret4 = pthread_create(&read_pid2,NULL,read_thread02,(void*)b);
	sleep(1);
    //子线程分离后,由系统回收
	//pthread_join(pid1,&hhh);//回收线程
	//pthread_join(pid2,&hhh);//回收线程
	//pthread_join(read_pid1,&hhh);//回收线程
	//pthread_join(read_pid2,&hhh);//回收线程
	while(1){
		sleep(1);
	}
	//关闭文件
	fclose(fp);
	return 0;
}

3.6死锁

概念:

避免方法:

  1. 锁越少越好,最好使用一把锁
  2. 调整好锁的顺序
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

FILE *fp;
void *func2(void *arg){
    pthread_detach(pthread_self());
    printf("This func2 thread\n");
    
    char str[]="I write func2 line\n";
    char c;
    int i=0;
    while(1){
        pthread_mutex_lock(&mutex);
        printf("%d,I got lock2\n",(int)arg);
        sleep(1);
        pthread_mutex_lock(&mutex2);
        printf("%d,I got 2 locks\n",(int)arg);

        pthread_mutex_unlock(&mutex2);
        pthread_mutex_unlock(&mutex1);
        sleep(10);

    }

    pthread_exit("func2 exit");

}

void *func(void *arg){
    pthread_detach(pthread_self());
    printf("This is func1 thread\n");
    char str[]="You read func1 thread\n";
    char c;
    int i=0;
    while(1){
        pthread_mutex_lock(&mutex);
        printf("%d,I got lock1\n",(int)arg);
        sleep(1);
        pthread_mutex_lock(&mutex2);
        printf("%d,I got 2 locks\n",(int)arg);

        pthread_mutex_unlock(&mutex2);
        pthread_mutex_unlock(&mutex);
        sleep(10);

    }
    pthread_exit("func1 exit");
}


int main(){
    pthread_t tid,tid2;
    void *retv;
    int i;
    fp = fopen("1.txt","a+");
    if(fp==NULL){
        perror("fopen");
        return 0;
    }
    pthread_create(&tid,NULL,func,1);
    pthread_create(&tid2,NULL,func2,2);

    while(1){    
        sleep(1);
    } 

}


总结

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值