【linux】线程同步 互斥量 死锁 读写锁

1.线程同步的概念

        所谓的同步,即为同时起步,协调一致。对同步的理解方式各不相同。比如:在设备中同步是指在两个设备之间规定的时间参考;数据库同步是指让两个或多个数据库保持一致,或者按需要部分保持一致;文件同步是指让两个文件或多个文件夹里的文件保持一致。

        而在编程中、通信中所说的同步是与生活中大家印象中的同步概念略有差异。“同”字应是指协同、协助、相互配合。

        同步即协同步调,对公共区域数据按预定的先后次序访问,防止数据混乱。

        同步的目的是为了避免数据混乱,解决与时间有关的错误。实际上,不仅线程时间需要同步,进程间、信号间也需要同步机制。因此,所有“多个控制流,共同操作一个共享资源”的情况下,都需要同步。

2.数据混乱的原因

        1.资源共享时(独享资源不会)

        2.调度随机(一位置数据访问会出现竞争)

        3.线程间缺乏必要的同步机制

        在上面三点中,前两点不能改变,欲提高效率,传递数据,资源必须共享。只要共享资源,就一定会出现竞争。只要存在竞争关系,数据就很容易很乱。就只能在第三点解决,使多个线程在访问共享资源的时候,出现互斥。

3.互斥量

        在linux中提供一把互斥锁mutex(也称为互斥量)。

        每一个线程在对资源操作前都尝试先加锁,成功加锁才能操作。操作结束解锁。

        资源还是共享的,线程间也还是竞争的。

        但通过“锁”就将资源的访问变成互斥操作,而后与时间有关的错误也不会在产生了。

        

 注意:在同一时刻,只能有一个线程持有该锁。

        比如:当线程A对某个全局变量加锁访问,B在访问前尝试加锁,拿不到锁,B阻塞。线程C不去加锁,而是直接访问该全局变量,依然能够访问,但会出现数据混乱。

        所以互斥锁实质上是操作系统提供的一把“建议锁”(又称“协同锁”),建议程序中有多线程访问共享资源的时候使用该机制。但并没有强制限定。

        因此即使有了mutex,如果有线程不按规则来访问数据,依然会造成数据混乱。

        例程:父子线程共同使用共享资源stdout,利用sleep造成时间差混乱。

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

void *f(void *arg)
{
	srand(time(NULL));
	while(1)
	{
		printf("hello ");
		sleep(rand() % 3);
		printf("world \n");
		sleep(rand() % 3);
	}
	return NULL;
}

int main(void)
{
	pthread_t tid;
	srand(time(NULL));
	pthread_create(&tid, NULL, f, NULL);
	while(1)
	{
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n ");
		sleep(rand() % 3);
	}
	pthread_join(tid,NULL);
	return 0;
}

         1.主要应用函数

                pthread_mutex_init函数

                pthread_mutex_destroy函数

                pthread_mutex_lock函数

                pthread_mutex_trylock函数

                pthread_mutex_unlock函数

                以上5个函数的返回值都是:成功返回0,失败返回错误号。

                pthread_mutex_t类型,本质是一个结构体。为简化理解,应用是可忽略其实现细节,简单当成整数看待。

                pthread_mutex_t     mutex;变量mutex只有两种取值1、0。

        2.使用mutex(互斥量、互斥锁)一般步骤

                1.pthread_mutex_t mutex:创建锁

                2.pthread_mutex_init:初始化

                3.pthread_mutex_lock:加锁

                4.访问共享数据(stdout)

                5.pthread_mutex_unlock:解锁

                6.pthread_mutex_destroy:销毁锁

        3.lock与unlock

                lock尝试加锁,如果加锁不成功,线程阻塞,阻塞到持有该互斥量的其他线程解锁为止

                unlock主动解锁函数。同时将阻塞在该锁上的所有线程全部唤醒,至于那个线程先被唤醒,取决于优先级、调度。默认:先阻塞、先唤醒

        4.lock与trylock

                lock加锁失败会阻塞,等待锁释放。

                trylock加锁失败直接返回错误号(如:EBUSY)不阻塞

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
//pthread_mutex_t 互斥锁类型名,
pthread_mutex_t mutex;//定义另一个互斥锁变量mutex,全局变量,所有线程可以共享使用
void *tfn2(void *arg)
{
//当某个线程,不进行对共享资源进行加锁操作时,仍旧会造成抢夺资源现象
	srand(time(NULL));
	while(1)
	{
		int ret=pthread_mutex_trylock(&mutex);
		if(ret!=0)
		{
			printf("pthread_mutx_trylock err:%s\n",strerror(ret));
		}
		else
		{
			printf("---tfn2()---print ");
			sleep(rand() % 3);
			printf("to stdout\n");
			sleep(rand() % 3);
			ret=pthread_mutex_unlock(&mutex);//解锁
			if(ret!=0)
			{
				fprintf(stderr,"pthread_mutex_unlock()error:%s\n",strerror(ret));
			}
		}
		printf("common tfn2()------\n");
		sleep(rand() % 3);
	}
}
void *tfn(void *arg)
{
	srand(time(NULL));
	while (1)
	{
		int ret=pthread_mutex_lock(&mutex);//加锁
		if(ret!=0)
		{
			fprintf(stderr,"pthread_mutex_lock() error:%s\n",strerror(ret));
		}
		printf("hello ");
		sleep(rand() % 3);
		printf("world\n");
//pthread_mutex_unlock(),对加锁成功的共享资源进行解锁
		ret=pthread_mutex_unlock(&mutex);//解锁
		if(ret!=0)
		{
			fprintf(stderr,"pthread_mutex_unlock() error:%s\n",strerror(ret));
		}
		sleep(rand() % 3);
	}
	return NULL;
}
int main(void)
{
	pthread_t tid;
	srand(time(NULL));
//pthread_mutex_init()初始化 互斥锁
	int ret=pthread_mutex_init(&mutex,NULL);//初始化锁
	if(ret!=0)
	{
		fprintf(stderr,"mutex init error:%s\n",strerror(ret));
	}
//pthread_create() 创建线程1
	ret=pthread_create(&tid, NULL, tfn, NULL);
	if(ret!=0)
	{
		fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
	}
//pthread_create() 创建线程2
	ret=pthread_create(&tid, NULL, tfn2, NULL);
	if(ret!=0)
	{
		fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
	}
	while (1)
	{ //pthread_mutex_lock()给已初始化过的互斥锁变量,(站在当前线程角度)对共享资源进行加锁操作
//如果加锁失败,则阻塞,也就是一直等待
		ret=pthread_mutex_lock(&mutex);//加锁
		if(ret!=0)
		{
			fprintf(stderr,"pthread_mutex_lock() error:%s\n",strerror(ret));
		}
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n");
//pthread_mutex_unlock(),对加锁成功的共享资源进行解锁
		ret=pthread_mutex_unlock(&mutex);//解锁
		if(ret!=0)
		{
			fprintf(stderr,"pthread_mutex_unlock() error:%s\n",strerror(ret));
		}
		sleep(rand() % 3);
	}
	pthread_join(tid, NULL);
	ret=pthread_mutex_destroy(&mutex);//销毁锁
	if(ret!=0)
	{
		fprintf(stderr,"pthread_mutex_destroy() error:%s\n",strerror(ret));
	}
	return 0;
}

 例程:父子线程共同使用共享资源stdout,利用sleep造成时间差混乱

               加锁进行共享资源控制

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex;
void *tfn(void *arg)
{
	srand(time(NULL));
	while (1)
	{
		pthread_mutex_lock(&mutex);//加锁
		printf("hello ");
		sleep(rand() % 3); /*模拟长时间操作共享资源 ,导致cpu易主,产生与时间有关的错误*/
		printf("world\n" );
		pthread_mutex_unlock(&mutex);//解锁
		sleep(rand() % 3);
	}
	return NULL;
}
int main(void)
{
	pthread_t tid;
	srand(time(NULL));
	int ret=pthread_mutex_init(&mutex,NULL);//初始化锁
	if(ret!=0)
	{
		fprintf(stderr,"mutex init error:%s\n",strerror(ret));
	}
	pthread_create(&tid, NULL, tfn, NULL);
	while (1)
	{
		pthread_mutex_lock(&mutex);//加锁
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n");
		pthread_mutex_unlock(&mutex);//解锁
		sleep(rand() % 3);
	}
	pthread_join(tid, NULL);
	pthread_mutex_destroy(&mutex);//销毁锁
return 0;
}

 注意事项:

        尽量保证锁的丽都,越小越好(访问共享数据之前,加锁。访问结束后,应立即解锁)

        互斥锁:本质是结构体,可以看做是整数,初值为1(pthread_mutex_init()函数调用成功)。

        加锁:--操作,阻塞线程

        解锁:++操作,唤醒阻塞在锁上的线程

        try锁:尝试加锁,成功--;失败,继续其他业务功能代码

4.死锁

        是使用锁不恰当导致的现象

        1.线程试图对同一个互斥量A加锁;两次。(连续调用pthread_mutex_lock两次及以上)

        2.线程1拥有A锁,请求获得B锁:线程2拥有B锁,请求获得A锁5.读写锁

        与互斥量类似,但读写锁允许更高的并行性。

        其特性为锁只有一把;写独占、读共享;写锁优先级高;

        1.读写锁状态

                特别强调。读写锁只有一把,但其具备两种状态:

                        1.读写模式下加锁状态(读锁)

                        2.写模式下加锁状态(写锁)。

         2.读写锁特征

                1.读写锁是“写模式加锁”成功时,其他线程尝加锁都会被阻塞

                2.读写锁是“读模式加锁”成功时,其他线程以写模式加锁会阻塞

                3.读写锁是“读模式加锁时”,既有试图以写模式加锁的线程,也有试图模式加锁的线程。读写锁会阻塞随后的读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高。

        读写锁也叫共享—独占锁。

        a.当读写锁已读模式锁住时,它是以共享模式锁住的,其他读线程可以读取内容

        b.当他以写模式锁住时,他是以独占模式锁住的,其他尝试操作的线程均会被阻塞。

        读写锁非常适合于对数据结构读的次数远大于写的情况。

         4.主要应用函数

                pthread_rwlock_init函数

                pthread_rwlock_destroy函数

                pthread_rwlock_rdlock函数

                pthread_rwlock_wrlock函数

                pthread_rwlock_tryrdlock函数

                pthread_rwlock_trywrlock函数

                pthread_rwlock_unlock函数

                以上7个函数的返回值都是,成功返回0,失败直接返回错误号

                pthread_rwlock_t   类型        用于定义一个读写锁变量

                pthread_rwlock_t   rwlock;

        初始化一把读写锁

                int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);

参1:传读写锁变量

参2:attr表示读写锁属性,通常使用默认值,传NULL即可

        销毁一把读写锁

                int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

参1:传读写锁变量

        以读方式请求读写锁(简称:请求读锁)        

        int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
        int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
        以写方式请求读写锁(简称:请求写锁)
                
        int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
        int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
解锁
        int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
例程:3个线程不定时写同一全局资源,5个线程不定时读同一全局资源
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
int counter;
pthread_rwlock_t rwlock;
void *th_write(void *arg)
{
	int t;
	int i = (long int)arg;
	while(1)
	{
		pthread_rwlock_wrlock(&rwlock);
		t = counter;
		sleep(1);
		printf("====write %d: %lu: counter=%d ++counter=%d\n",i,pthread_self(), t, ++counter);
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
	return NULL;
}
void *th_read(void *arg)
{
	int i = (long int)arg;
	while(1)
	{
		pthread_rwlock_rdlock(&rwlock);
		printf("----------------read %d: %lu: %d\n", i, pthread_self(),counter);
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
	return NULL;
}

int main(void)
{
	long int i;
	pthread_t tid[8];
	pthread_rwlock_init(&rwlock,NULL);
	for(i=0;i<3;i++)
	{
		pthread_create(&tid[i],NULL, th_write, (void *)i);
	}
	for(i=0;i<5;i++)
	{
		pthread_create(&tid[i+3], NULL, th_read, (void *)i);
	}
	for(i=0;i<8;i++)
	{
		pthread_join(tid[i], NULL);
	}
	pthread_rwlock_destroy(&rwlock);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值