144 Linux 系统编程21 ,线程同步,互斥锁mutex,读写锁pthread_rwlock_t,死锁问题,条件变量,生产者消费者条件变量模型,信号量,生产者消费者信号量模型

一 线程同步:保证访问的共享资源不会发生数据混乱

二 数据混乱原因 以及解决方案:

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

2. 调度随机(意味着数据访问会出现竞争)

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

以上3点中,前两点不能改变,欲提高效率,传递数据,资源必须共享。只要共享资源,就一定会出现竞争。只要存在竞争关系,数据就很容易出现混乱。

所以只能从第三点着手解决。使多个线程在访问共享资源的时候,出现互斥

三,互斥锁,也叫互斥量 -- mutex

使用方法以及原理

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

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

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

注意的是:如果有5个线程都同时访问 共享资源,那么这5个线程要使用一把锁子,谁拿到了,谁去访问。

使用前提条件  sudo apt-get install manpages-posix-dev

//我们使用man pthread_mutex_init,发现提示没有pthread_mutex_init

//查了下,应该是如果要使用mutext 要安装 manpages-posix-dev

//sudo apt-get install manpages-posix-dev

四 主要应用函数:

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。

pthread_mutex_init函数

初始化一个互斥锁(互斥量) ---> 初值可看作1

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

参1:传出参数,调用时应传 &mutex

restrict关键字:只用于限制指针,告诉编译器,所有修改该指针指向内存中内容的操作,只能通过本指针完成。不能通过除本指针以外的其他变量或指针修改

参2:互斥量属性。是一个传入参数,通常传NULL,选用默认属性(线程间共享)。 参APUE.12.4同步属性

  1. 静态初始化:如果互斥锁 mutex 是静态分配的(定义在全局,或加了static关键字修饰),可以直接使用宏进行初始化。e.g.  pthead_mutex_t muetx = PTHREAD_MUTEX_INITIALIZER;
  2. 动态初始化:局部变量应采用动态初始化。e.g.  pthread_mutex_init(&mutex, NULL)

pthread_mutex_destroy函数

销毁一个互斥锁

int pthread_mutex_destroy(pthread_mutex_t *mutex);

pthread_mutex_lock函数

加锁。可理解为将mutex--(或 -1),操作后mutex的值为0。

int pthread_mutex_lock(pthread_mutex_t *mutex);

pthread_mutex_unlock函数

解锁。可理解为将mutex ++(或 +1),操作后mutex的值为1。

int pthread_mutex_unlock(pthread_mutex_t *mutex);

pthread_mutex_trylock函数

尝试加锁

int pthread_mutex_trylock(pthread_mutex_t *mutex);

五 加锁与解锁

lock与unlock:

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

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

例如:T1 T2 T3 T4 使用一把mutex锁。T1加锁成功,其他线程均阻塞,直至T1解锁。T1解锁后,T2 T3 T4均被唤醒,并自动再次尝试加锁。

可假想mutex锁 init成功初值为1。 lock 功能是将mutex--。而unlock则将mutex++。

lock与trylock:

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

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

六 mutex 互斥锁例子:

例子一:

//mutex 互斥锁例子
//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。

//我们让主线程和子线程 能打印 "hello world",一个能打印 "HELLO WORLD"
//我们使用man pthread_mutex_init,发现提示没有pthread_mutex_init
//查了下,应该是如果要使用mutext 要安装 manpages-posix-dev
//sudo apt-get install manpages-posix-dev

pthread_mutex_t mutex;//互斥锁mutex,是各个线程共享的,因此mutex需要是全局变量

void* startthread(void * args) {
	srand(time(NULL));
	while (1) {

		pthread_mutex_lock(&mutex);
		printf("hello ");
		sleep(rand() % 3);
		printf("world\n");
		pthread_mutex_unlock(&mutex);
		sleep(rand() % 3);
	}

	return NULL;
}
int main() {

	int ret = 0;
	pthread_t pth;
	pthread_mutex_init(&mutex,NULL);//1. init mutex 注意这里,init mutex需要在主线程 和子线程 使用 lock之前
	pthread_create(&pth,NULL,startthread,NULL);

	while (1) {

		pthread_mutex_lock(&mutex);//2. lock mutex
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n");
		pthread_mutex_unlock(&mutex);//3.unlock mutex
		sleep(rand() % 3);
	}
	pthread_mutex_destroy(&mutex);//4.  destory mutex

	return ret;
}

例子二:在主线程打印10次后,使用主线程cancel子线程。

pthread_mutex_t mutex;//互斥锁mutex,是各个线程共享的,因此mutex需要是全局变量

void* startthread(void * args) {
	srand(time(NULL));
	while (1) {

		pthread_mutex_lock(&mutex);
		printf("hello ");
		sleep(rand() % 3);
		printf("world\n");
		pthread_mutex_unlock(&mutex);
		sleep(rand() % 3);
	}

	return NULL;
}
int main() {

	int ret = 0;
	pthread_t pth;
	pthread_mutex_init(&mutex,NULL);//1. init mutex 注意这里,init mutex需要在主线程 和子线程 使用 lock之前
	pthread_create(&pth,NULL,startthread,NULL);
	int i = 10;
	while (i>0) {

		pthread_mutex_lock(&mutex);//2. lock mutex
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n");
		i--;
		pthread_mutex_unlock(&mutex);//3.unlock mutex
		sleep(rand() % 3);

	}
	//当主线程打印10次后,在主线程中将子线程 cancel掉。
	pthread_cancel(pth);
	//注意这里,一旦将子线程cancel,有可能后续的destroy可能早于 子线程完成,也就是说,有可能mutex都被destory了,子线程的逻辑还没有走完,因此在cancel后,应该是join
	pthread_join(pth, NULL);
	pthread_mutex_destroy(&mutex);//4.  destory mutex

	pthread_exit(NULL);
	return ret;
	//结果

	//hunandede@hunandede-virtual - machine:~/ projects / linuxcpp$ . / main
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	HELLO WORLD
	//	HELLO WORLD
	//	hello world
	//	HELLO WORLD
	//	hello world
	//	hunandede@hunandede-virtual - machine:~/ projects / linuxcpp$

}

七 死锁问题

1. 线程试图对同一个互斥量A加锁两次。

例子

lock mutex 二次,很显然,要lock之前,必须让当前拥有锁子的线程unlock,但是不好意思,自己就是这个线程,因此死锁

//七 死锁问题 1. 线程试图对同一个互斥量A加锁两次。
void* startthread1(void * args) {
	srand(time(NULL));
	while (1) {

		pthread_mutex_lock(&mutex);
		printf("hello ");
		sleep(rand() % 3);
		printf("world\n");
		pthread_mutex_unlock(&mutex);
		sleep(rand() % 3);
	}

	return NULL;
}
int main() {

	int ret = 0;
	pthread_t pth;
	pthread_mutex_init(&mutex, NULL);//1. init mutex 注意这里,init mutex需要在主线程 和子线程 使用 lock之前
	pthread_create(&pth, NULL, startthread1, NULL);
	sleep(1);
	int i = 10;
	while (i > 0) {

		pthread_mutex_lock(&mutex);//2. lock mutex
		pthread_mutex_lock(&mutex);//2. lock mutex 第二次lock,很显然,要lock之前,必须让当前拥有锁子的线程unlock,但是不好意思,自己就是这个线程,因此死锁
		printf("HELLO ");
		sleep(rand() % 3);
		printf("WORLD\n");
		i--;
		pthread_mutex_unlock(&mutex);//3.unlock mutex
		sleep(rand() % 3);

	}
	//当主线程打印10次后,在主线程中将子线程 cancel掉。
	pthread_cancel(pth);
	//注意这里,一旦将子线程cancel,有可能后续的destroy可能早于 子线程完成,也就是说,有可能mutex都被destory了,子线程的逻辑还没有走完,因此在cancel后,应该是join
	pthread_join(pth, NULL);
	pthread_mutex_destroy(&mutex);//4.  destory mutex

	pthread_exit(NULL);
	return ret;
	//结果

}

2. 线程1拥有A锁,请求获得B锁;线程2拥有B锁,请求获得A锁

注意的是:按照理解,

主线程应该是 lock的顺序应该是:

pthread_mutex_lock(mutex);

pthread_mutex_lock(mutex2);

子线程应该是 lock的顺序应该是:

pthread_mutex_lock(mutex2);

pthread_mutex_lock(mutex);

会导致死锁,这也很好理解,

主 lock mutex,请求 lock mutex2 

但是这时候 

子lock mutex2,请求lock mutex

问题发生

pthread_mutex_t mutex;//互斥锁mutex,是各个线程共享的,因此mutex需要是全局变量

pthread_mutex_t mutex2;
//七 死锁问题 2 线程1拥有A锁,请求获得B锁;线程2拥有B锁,请求获得A锁
void* startthread2(void * args) {
	srand(time(NULL));
	while (1) {

		pthread_mutex_lock(&mutex2);
		pthread_mutex_lock(&mutex);

		printf("hello ");
		sleep(rand() % 1);
		printf("world\n");
		pthread_mutex_unlock(&mutex2);
		pthread_mutex_unlock(&mutex);

		sleep(rand() % 1);
	}

	return NULL;
}
int main() {

	int ret = 0;
	pthread_t pth;
	pthread_mutex_init(&mutex, NULL);//1. init mutex 注意这里,init mutex需要在主线程 和子线程 使用 lock之前
	pthread_mutex_init(&mutex2, NULL);
	pthread_create(&pth, NULL, startthread2, NULL);
	sleep(1);
	int i = 10;
	while (1) {

		pthread_mutex_lock(&mutex);//2. lock mutex
		pthread_mutex_lock(&mutex2);//3. lock mutex2 
		printf("HELLO ");
		sleep(rand() % 1);
		printf("WORLD\n");
		i--;
		pthread_mutex_unlock(&mutex);//4.unlock mutex
		pthread_mutex_unlock(&mutex2);//5.unlock mutex2
		sleep(rand() % 1);

	}
	//当主线程打印10次后,在主线程中将子线程 cancel掉。
	pthread_cancel(pth);
	//注意这里,一旦将子线程cancel,有可能后续的destroy可能早于 子线程完成,也就是说,有可能mutex都被destory了,子线程的逻辑还没有走完,因此在cancel后,应该是join
	pthread_join(pth, NULL);
	pthread_mutex_destroy(&mutex);//4.  destory mutex

	pthread_exit(NULL);
	return ret;
	//结果:执行一会后会死锁

}

死锁问题的解决方案:

1.在写代码的时候如果用到多个锁子,请自行保证锁子的顺序一样

2.使用trylock,判定返回值,如果需要的锁子被锁住了,则将自己已经锁了的,立即释放,实际上,C++的锁子已经实现了这种功能

 pthread_mutex_trylock(&mymutex1)会尝试加锁,如果该互斥锁已经锁定,则返回一个不为0
 得错误值,如果该互斥锁没有锁定,则返回0,表示尝试加锁成功

八 读写锁pthread_rwlock_t

与互斥量类似,但读写锁允许更高的并行性。其特性为:写独占,读共享

读写锁状态:

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

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

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

读写锁特性:

  1. 读写锁是“写模式加锁”时, 解锁前,所有对该锁加锁的线程都会被阻塞。
  2. 读写锁是“读模式加锁”时, 如果线程以读模式对其加锁会成功;如果线程以写模式加锁会阻塞。
  3. 读写锁是“读模式加锁”时, 既有试图以写模式加锁的线程,也有试图以读模式加锁的线程。那么读写锁会阻塞随后的读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高

读写锁也叫共享-独占锁。当读写锁以读模式锁住时,它是以共享模式锁住的;当它以写模式锁住时,它是以独占模式锁住的。写独占、读共享。

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

主要应用函数:

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;

pthread_rwlock_init函数

初始化一把读写锁

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

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

pthread_rwlock_destroy函数

销毁一把读写锁

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

pthread_rwlock_rdlock函数

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

    int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);

pthread_rwlock_wrlock函数

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

    int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

pthread_rwlock_unlock函数

解锁

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

pthread_rwlock_tryrdlock函数

非阻塞以读方式请求读写锁(非阻塞请求读锁)

int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

pthread_rwlock_trywrlock函数

非阻塞以写方式请求读写锁(非阻塞请求写锁)

int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);

读写锁示例

//pthread_rwlock_init函数
//pthread_rwlock_destroy函数
//pthread_rwlock_rdlock函数
//pthread_rwlock_wrlock函数
//pthread_rwlock_tryrdlock函数
//pthread_rwlock_trywrlock函数
//pthread_rwlock_unlock函数

pthread_rwlock_t rwlock; //读写锁也要写成全局变量。

int grwlock_data = 100;

void * startroutineread(void * args) {

	long long i = (long long)args;

	pthread_rwlock_rdlock(&rwlock);
	printf("startroutineread 子线程 i = %d, 子线程id = %lu, 子线程的进程 = %lu,  grwlock_data = %d \n",i,pthread_self(),getpid(), grwlock_data);
	pthread_rwlock_unlock(&rwlock);
	sleep(1);
	return NULL;
}

void * startroutinewrite(void * args) {

	long long i = (long long)args;
	pthread_rwlock_wrlock(&rwlock);
	grwlock_data = i + grwlock_data;
	printf("startroutinewrite 子线程 i = %d, 子线程id = %lu, 子线程的进程 = %lu, grwlock_data = %d\n", i, pthread_self(), getpid(), grwlock_data);
	pthread_rwlock_unlock(&rwlock);
	sleep(1);
	return NULL;
}
int main() {
	int ret = 0;
	pthread_rwlock_init(&rwlock, NULL);//同样,rw_lock_init也要在创建线程之前,
	//这里弄了6个读取的thread,6个写的thread
	int i = 0;
	pthread_t pth[12];
	for (; i < 6; ++i) {
		pthread_create(&pth[i],NULL, startroutineread,(void *)i);
	}
	for (; i < 12; ++i) {
		pthread_create(&pth[i], NULL, startroutinewrite, (void *)i);
	}

	//在这里,我们设计的是主线程不用去读写,只用将读写程序弄出来就行。
	int j = 0;
	for (; j < 12;++j) {
		pthread_join(pth[j],NULL);
	}

	pthread_rwlock_destroy(&rwlock);
	pthread_exit(NULL);
	return ret;

	//结果
	//hunandede@hunandede-virtual - machine:~/ projects / linuxcpp$ . / main
	//	startroutineread 子线程 i = 0, 子线程id = 139859678140160, 子线程的进程 = 16113, grwlock_data = 100
	//	startroutineread 子线程 i = 1, 子线程id = 139859669747456, 子线程的进程 = 16113, grwlock_data = 100
	//	startroutineread 子线程 i = 2, 子线程id = 139859661354752, 子线程的进程 = 16113, grwlock_data = 100
	//	startroutineread 子线程 i = 3, 子线程id = 139859652962048, 子线程的进程 = 16113, grwlock_data = 100
	//	startroutinewrite 子线程 i = 6, 子线程id = 139859553408768, 子线程的进程 = 16113, grwlock_data = 106
	//	startroutinewrite 子线程 i = 7, 子线程id = 139859545016064, 子线程的进程 = 16113, grwlock_data = 113
	//	startroutineread 子线程 i = 5, 子线程id = 139859561801472, 子线程的进程 = 16113, grwlock_data = 113
	//	startroutineread 子线程 i = 4, 子线程id = 139859570194176, 子线程的进程 = 16113, grwlock_data = 113
	//	startroutinewrite 子线程 i = 10, 子线程id = 139859519837952, 子线程的进程 = 16113, grwlock_data = 123
	//	startroutinewrite 子线程 i = 11, 子线程id = 139859511445248, 子线程的进程 = 16113, grwlock_data = 134
	//	startroutinewrite 子线程 i = 9, 子线程id = 139859528230656, 子线程的进程 = 16113, grwlock_data = 143
	//	startroutinewrite 子线程 i = 8, 子线程id = 139859536623360, 子线程的进程 = 16113, grwlock_data = 151

}

九 条件变量:

条件变量本身不是锁!但它也可以造成线程阻塞。通常与互斥锁配合使用。给多线程提供一个会合的场所。

主要应用函数:

pthread_cond_init函数

pthread_cond_destroy函数

pthread_cond_wait函数

pthread_cond_timedwait函数

pthread_cond_signal函数

pthread_cond_broadcast函数

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

pthread_cond_t类型 用于定义条件变量

pthread_cond_t cond;

pthread_cond_init函数

初始化一个条件变量

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

参2:attr表条件变量属性,通常为默认值,传NULL即可

也可以使用静态初始化的方法,初始化条件变量:

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

pthread_cond_destroy函数

销毁一个条件变量

int pthread_cond_destroy(pthread_cond_t *cond);

pthread_cond_wait函数 核心函数

阻塞等待一个条件变量

    int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

函数作用:

  1. 阻塞等待条件变量cond(参1)满足
  2. 释放已掌握的互斥锁(解锁互斥量)相当于pthread_mutex_unlock(&mutex);

 1.2.两步为一个原子操作。

     3. 当被唤醒,pthread_cond_wait函数返回时,解除阻塞并重新申请获取互斥锁pthread_mutex_lock(&mutex);

pthread_cond_timedwait函数

限时等待一个条件变量

int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);

参3: 参看man sem_timedwait函数,查看struct timespec结构体。

struct timespec {

time_t tv_sec; /* seconds */ 秒

long   tv_nsec; /* nanosecondes*/ 纳秒

}

形参abstime:绝对时间。

如:time(NULL)返回的就是绝对时间。而alarm(1)是相对时间,相对当前时间定时1秒钟。

struct timespec t = {1, 0};

pthread_cond_timedwait (&cond, &mutex, &t); 只能定时到 1970年1月1日 00:00:01秒(早已经过去) 

正确用法:

time_t cur = time(NULL); 获取当前时间。

struct timespec t; 定义timespec 结构体变量t

t.tv_sec = cur+1; 定时1秒

pthread_cond_timedwait (&cond, &mutex, &t); 传参 参APUE.11.6线程同步条件变量小节

在讲解setitimer函数时我们还提到另外一种时间类型:

        struct timeval {

             time_t      tv_sec;  /* seconds */ 秒

             suseconds_t tv_usec; /* microseconds */ 微秒

        };

pthread_cond_signal函数

唤醒至少一个阻塞在条件变量上的线程

int pthread_cond_signal(pthread_cond_t *cond);

pthread_cond_broadcast函数

唤醒全部阻塞在条件变量上的线程

    int pthread_cond_broadcast(pthread_cond_t *cond);

生产者消费者条件变量模型

线程同步典型的案例即为生产者消费者模型,而借助条件变量来实现这一模型,是比较常见的一种方法。假定有两个线程,一个模拟生产者行为,一个模拟消费者行为。两个线程同时操作一个共享资源(一般称之为汇聚),生产向其中添加产品,消费者从中消费掉产品。

看如下示例,使用条件变量模拟生产者、消费者问题:

//九 条件变量:
//条件变量本身不是锁!但它也可以造成线程阻塞。通常与互斥锁配合使用。给多线程提供一个会合的场所。
//
//主要应用函数:
//pthread_cond_init函数
//pthread_cond_destroy函数
//pthread_cond_wait函数
//pthread_cond_timedwait函数
//pthread_cond_signal函数
//pthread_cond_broadcast函数

typedef struct promsg {
	promsg * next;//链表结构,指向下一个promsg
	int num; // 真正的数据
}promsg;

pthread_cond_t pcond; //条件变量,所有线程共享一个使用
pthread_mutex_t mutex6; // 互斥锁,所有线程共享一个使用
promsg *head;///共享数据

//3.消费者线程
void * startroutinecustomer(void * args) {
	struct promsg *cusmp;//要取出来的数据
	while (1) {//这个循环不停的消费数据
		pthread_mutex_lock(&mutex6);//lock住后, 
		while (head==NULL) {//注意这里要使用while循环,因为在多个消费者的case下,有可能多个消费者线程都都走到pthread_cond_wait这一步,cond条件成立后,多个消费者抢夺 mutex6,
			//当共享数据中没有数据时,阻塞等待条件变量pcond(参1)满足,释放mutex6锁
			//当在生产者线程生产出来数据的时候,
			//生产者线程会调用pthread_cond_signal函数 或者 pthread_cond_broadcast函数,唤醒阻塞的wait
			//当被唤醒,会解除阻塞,然后重新申请获取mutex6锁。
			pthread_cond_wait(&pcond, &mutex6);
		}
		cusmp = head; //将共享数据的头部得到
		head = cusmp->next; //让共享数据的头部指向下一个数据。也就是模拟消费掉了一个数据

		pthread_mutex_unlock(&mutex6);//解锁
		cout << "cusmp->num = " << cusmp->num << endl;
		free(cusmp);//释放资源
		sleep(rand() % 5);
	}
}

//4.生产者线程
void * startroutineproductor(void * args) {
	promsg *msg;
	while (1) {//这个线程不停的生产数据
		msg =(promsg *) malloc(sizeof(promsg));
		memset(msg, 0, sizeof(promsg));
		msg->num = rand() % 20;//模拟生成一个数据
		cout << "pro num = " << msg->num << endl;

		pthread_mutex_lock(&mutex6);//锁了


		msg->next = head;//头插法,让新建的数据msg的next指向head
		head = msg;//让新建的数据整体变成head


		pthread_mutex_unlock(&mutex6);//解锁
		pthread_cond_signal(&pcond);//将等待在该条件变量上的一个线程唤醒
		sleep(rand() % 5);
	}
}

int main() {
	int ret = 0;
	pthread_t cid, pid;
	//0.随机种子数,这个和当前的知识点关系不大,主要是为了在子线程中随机生成数据
	srand(time(NULL));
	//1.在创建thread之前将 cond init
	pthread_cond_init(&pcond,NULL);
	pthread_mutex_init(&mutex6, NULL);


	//2.启动消费者线程 	//启动生产者线程
	pthread_create(&cid, NULL, startroutinecustomer, NULL);
	pthread_create(&pid, NULL, startroutineproductor, NULL);


	//5.销毁pcond,mutex6
	pthread_cond_destroy(&pcond);
	pthread_mutex_destroy(&mutex6);


	//6.阻塞回收 cid 和 pid
	pthread_join(cid,NULL);
	pthread_join(pid, NULL);


	pthread_exit(NULL);
	return ret;
}

简略版

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

struct msg {
    struct msg *next;
    int num;
};
struct msg *head;

pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *consumer(void *p)
{
    struct msg *mp;
    for (;;) {
        pthread_mutex_lock(&lock);
        while (head == NULL) {           //头指针为空,说明没有节点    可以为if吗
            pthread_cond_wait(&has_product, &lock);
        }
        mp = head;      
        head = mp->next;    			//模拟消费掉一个产品
        pthread_mutex_unlock(&lock);

        printf("-Consume ---%d\n", mp->num);
        free(mp);
        sleep(rand() % 5);
    }
}
void *producer(void *p)
{
    struct msg *mp;
    while (1) {
        mp = malloc(sizeof(struct msg));
        mp->num = rand() % 1000 + 1;        //模拟生产一个产品
        printf("-Produce ---%d\n", mp->num);

        pthread_mutex_lock(&lock);
        mp->next = head;
        head = mp;
        pthread_mutex_unlock(&lock);

        pthread_cond_signal(&has_product);  //将等待在该条件变量上的一个线程唤醒
        sleep(rand() % 5);
    }
}
int main(int argc, char *argv[])
{
    pthread_t pid, cid;
    srand(time(NULL));

    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);
    return 0;
}											

条件变量的优点:

相较于mutex而言,条件变量可以减少竞争。

如直接使用mutex,除了生产者、消费者之间要竞争互斥量以外,消费者之间也需要竞争互斥量,但如果汇聚(链表)中没有数据,消费者之间竞争互斥锁是无意义的。有了条件变量机制以后,只有生产者完成生产,才会引起消费者之间的竞争。提高了程序效率。

十 信号量 可以用于进程和线程间的同步。

进化版的互斥锁(1 --> N)

由于互斥锁的粒度比较大,如果我们希望在多个线程间对某一对象的部分数据进行共享,使用互斥锁是没有办法实现的,只能将整个数据对象锁住。这样虽然达到了多线程操作共享数据时保证数据正确性的目的,却无形中导致线程的并发性下降。线程从并行执行,变成了串行执行。与直接使用单进程无异。

信号量,是相对折中的一种处理方式,既能保证同步,数据不混乱,又能提高线程并发。

主要应用函数:

sem_init函数

sem_destroy函数

sem_wait函数

sem_trywait函数

sem_timedwait函数

sem_post函数

以上6 个函数的返回值都是:成功返回0, 失败返回-1,同时设置errno。(注意,它们没有pthread前缀)

sem_t类型,本质仍是结构体。但应用期间可简单看作为整数,忽略实现细节(类似于使用文件描述符)。

sem_t sem; 规定信号量sem不能 < 0。头文件 <semaphore.h>

信号量基本操作:

sem_wait: 1. 信号量大于0,则信号量-- (类比pthread_mutex_lock)

  | 2. 信号量等于0,造成线程阻塞

对应

  |

sem_post: 将信号量++,同时唤醒阻塞在信号量上的线程 (类比pthread_mutex_unlock)

但,由于sem_t的实现对用户隐藏,所以所谓的++、--操作只能通过函数来实现,而不能直接++、--符号。

信号量的初值,决定了占用信号量的线程的个数。

sem_init函数

初始化一个信号量

int sem_init(sem_t *sem, int pshared, unsigned int value);

参1:sem信号量

参2:pshared取0用于线程间;取非0(一般为1)用于进程间

参3:value指定信号量初值

sem_destroy函数

销毁一个信号量

int sem_destroy(sem_t *sem);

sem_wait函数

给信号量加锁 --

int sem_wait(sem_t *sem);

sem_post函数

给信号量解锁 ++

 int sem_post(sem_t *sem);

sem_trywait函数

尝试对信号量加锁 -- (与sem_wait的区别类比lock和trylock)

 int sem_trywait(sem_t *sem);

sem_timedwait函数

限时尝试对信号量加锁 --

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

参2:abs_timeout采用的是绝对时间。

定时1秒:

time_t cur = time(NULL); 获取当前时间。

struct timespec t; 定义timespec 结构体变量t

t.tv_sec = cur+1; 定时1秒

t.tv_nsec = t.tv_sec +100;

sem_timedwait(&sem, &t); 传参

生产者消费者信号量模型

【练习】:使用信号量完成线程间同步,模拟生产者,消费者问题。

//十 使用sem完成生产者消费者问题,规定空间只有5个那么大,当生产5之后就满了
//同样,最多消费的也就只有5个就没有啥可以消费的了



sem_t start_num;//产品信号量
sem_t blank_num;//空格子信号量
int queue[5];//全局数组,共享数据,在代码中会实现成环形队列



//生产者线程
void * prosemmethod(void * args) {
	int i = 0;
	while (1) {
		sem_wait(&blank_num); //生产者将空格子信号量 bleak_num --,为0则阻塞等待
		queue[i] = rand() % 1000 + 1;
		printf("---product--- %d\n",queue[i]);
		sem_post(&start_num); //将产品信号量 start_num ++ 
		i = (i + 1) % 5;//借助下标实现环形队列
		sleep(rand() % 1);
	}

	return NULL;
}

//消费者线程
void * cussemmethod(void * args) {
	int i = 0;
	while (1) {
		sem_wait(&start_num);//消费者将 产品信号量start_num  --,如果start_num为0则阻塞等待
		printf("---customer--- %d\n", queue[i]);
		queue[i] = -1;//变成-1就相当于我们消费了这个产品

		sem_post(&blank_num);//将空格信号量++
		i = (i + 1) % 5;//借助下标实现环形队列
		sleep(rand() % 3); //这里让消费的慢一点
	}
	return NULL;
}

int main() {

	int ret = 0;
	pthread_t psemid,csemid;
	sem_init(&start_num, 0, 0);//注意这里,产品数开始为0,没有产品
	sem_init(&blank_num, 0, 5);
	pthread_create(&psemid, NULL, prosemmethod, NULL);
	pthread_create(&csemid, NULL, cussemmethod, NULL);


	pthread_join(psemid,NULL);
	pthread_join(csemid, NULL);
	sem_destroy(&start_num);
	sem_destroy(&blank_num);

	pthread_exit(NULL);
	return ret;
}

hunandede@hunandede-virtual-machine:~/projects/linuxcpp$ ./main
---product--- 384
---customer--- 384
---product--- 916
---customer--- 916
---product--- 387
---product--- 650
---product--- 363
---product--- 691
---product--- 764
---customer--- 387
---product--- 427
---customer--- 650
---product--- 212
---customer--- 363
---product--- 430
---customer--- 691
---product--- 863
---customer--- 764
---product--- 136
---customer--- 427
---product--- 23
---customer--- 212
---product--- 168
---customer--- 430
---product--- 12
---customer--- 863
---product--- 374
---customer--- 136
---product--- 785
---customer--- 23
---product--- 325
---customer--- 168
---product--- 414
---customer--- 12
---product--- 981
---customer--- 374
---product--- 863
---customer--- 785
---product--- 282

分析:

规定: 如果□中有数据,生产者不能生产,只能阻塞。

如果□中没有数据,消费者不能消费,只能等待数据。

定义两个信号量:S满 = 0, S空 = 1 (S满代表满格的信号量,S空表示空格的信号量,程序起始,格子一定为空)

所以有: T生产者主函数 { T消费者主函数 {

      sem_wait(S空);      sem_wait(S满);

     生产....        消费....

      sem_post(S满);      sem_post(S空);

} }

假设: 线程到达的顺序是:T生、T生、T消。

那么: T生1 到达,将S空-1,生产,将S满+1

T生2 到达,S空已经为0, 阻塞

T消  到达,将S满-1,消费,将S空+1

三个线程到达的顺序是:T生1、T生2、T消。而执行的顺序是T生1、T消、T生2

这里,S空 表示空格子的总数,代表可占用信号量的线程总数-->1。其实这样的话,信号量就等同于互斥锁。

但,如果S空=2、3、4……就不一样了,该信号量同时可以由多个线程占用,不再是互斥的形式。因此我们说信号量是互斥锁的加强版。

【推演练习】: 理解上述模型,推演,如果是两个消费者,一个生产者,是怎么样的情况。

【作业】:结合生产者消费者信号量模型,揣摩sem_timedwait函数作用。编程实现,一个线程读用户输入, 另一个线程打印“hello world”。如果用户无输入,则每隔5秒向屏幕打印一个“hello world”;如果用户有输入,立刻打印“hello world”到屏幕。

  • 23
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值