linux多线程-互斥&条件变量与同步
多线程代码问题描述
我们都知道,进程是操作系统对运行程序资源分配的基本单位,而线程是程序逻辑,调用的基本单位。在多线程的程序中,多个线程共享临界区资源,那么就会有问题:
比如
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> int g_val = ;
void * test1(void* args)
{
g_val = ;
printf("in %s: g_val = %d\n",__func__, g_val);
}
void * test2(void* args)
{
sleep();
printf("in %s: g_val = %d\n",__func__,g_val);
}
int main(int argc, char const *argv[])
{
pthread_t id1,id2;
pthread_create(&id1,NULL,test1,NULL);
pthread_create(&id2,NULL,test2,NULL);
pthread_join(id1,NULL);
pthread_join(id2,NULL);
return ;
}
由次我们可以看到,线程1修改了全局变量,而线程2中页跟着改变了。
那么,对于这个问题进行放大,我们就会找到多线程存在的问题。如下
#include <stdio.h>
#include <pthread.h>
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int g_val = ;
void* add(void *argv)
{
for(int i = ; i < ; ++i)
{
// g_val++;
// pthread_mutex_lock(&lock);
int tmp = g_val;
g_val = tmp+;
// pthread_mutex_unlock(&lock);
}
} int main(int argc, char const *argv[])
{
pthread_t id1,id2; pthread_create(&id1,NULL,add,NULL);
pthread_create(&id2,NULL,add,NULL); pthread_join(id1,NULL);
pthread_join(id2,NULL); printf("%d\n",g_val);
return ;
}

在上面代码中,我们执行两个线程分别对全局变量累加5000次,但是得到的结果却是不确定的。这是因为,在多线程程序中,线程调度使得线程间进行切换执行,如果当线程1将数据从内存读入cpu正在准备累加时,调度器切换线程2执行,此时,线程2获取的值是未累加的。那么,当两个线程都执行完本次累加后,实际值只增加了1。所以就会产生多次执行,结果不确定性。
注:代码中没有直接g_val++,而选择了tmp过度就是为了产生非原子操作,让调度过程处于累加未完时。
那么解决这个问题,就需要互斥操作了。
我们首先来谈互斥量mutex
通过互斥量实现线程锁,在每个线程累加之前,进行临界资源的锁操作,在结束时解锁,那么就能保证目标的实现了。
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int g_val = ;
void* add(void *argv)
{
for(int i = ; i < ; ++i)
{
// g_val++;
pthread_mutex_lock(&lock);
int tmp = g_val;
g_val = tmp+;
pthread_mutex_unlock(&lock);
}
} int main(int argc, char const *argv[])
{
pthread_t id1,id2; pthread_create(&id1,NULL,add,NULL);
pthread_create(&id2,NULL,add,NULL); pthread_join(id1,NULL);
pthread_join(id2,NULL); printf("%d\n",g_val);
return ;
}

关于互斥锁的实现,在linux中实现如下

条件变量
问题场景描述
假设我们现在需要做一个生产者消费者模型,生产者对带有头节点的链表头插方式push_front生产数据,消费者调用pop_front消费数据.而生产者可能动作比较慢,这时就会有问题。
生产者生产一个数据时间,消费者可能迫切需求。因此,一直轮寻申请锁资源,以便进行消费。所以就会产生多次不必的锁资源申请释放动作。影响系统性能。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
typedef struct node
{
int _data;
struct node *_next;
}node_t,* node_p,**node_pp; node_p head = NULL; node_p alloc_node(int data)
{
node_p ret = (node_p)malloc(sizeof(node_t));
ret->_data = data;
ret->_next = NULL;
return ret;
} void init(node_pp phead)
{
*phead = alloc_node();
} void push_front(node_p head,int data)
{
node_p tmp = alloc_node(data);
tmp->_next = head->_next;
head->_next = tmp;
} void pop_front(node_p head, int * pdata)
{
if(head->_next!=NULL)
{
node_p tmp = head->_next;
head->_next = tmp->_next; *pdata = tmp->_data;
free(tmp);
}
} void show(node_p head)
{
node_p cur = head->_next;
while(cur)
{
printf("%d->", cur->_data);
cur = cur->_next;
}
printf("\n");
} //消费者
void * consumer(void *argv)
{
int data;
while()
{
pthread_mutex_lock(&lock);
// while(head->_next==NULL)
if(head->_next==NULL)
{
printf("producter is not ready\n");
// pthread_cond_wait(&cond,&lock);
// break;
}
else{
printf("producter is ready...\n");
pop_front(head,&data);
printf("%s data = %d \n",__func__, data);
}
pthread_mutex_unlock(&lock); sleep();
}
} void * producter(void * argv)
{
int data = rand()%;
while()
{
sleep();
pthread_mutex_lock(&lock);
push_front(head,data);
printf("%s data :: %d\n",__func__, data);
pthread_mutex_unlock(&lock);
// pthread_cond_signal(&cond);
}
} int main(int argc, char const *argv[])
{
init(&head); pthread_t id1,id2; pthread_create(&id1,NULL,consumer,NULL);
pthread_create(&id2,NULL,producter,NULL); pthread_join(id1,NULL);
pthread_join(id2,NULL);
}

由上,我们发现。生产者生叉一个数据之后,消费者总是会多次进行锁资源申请并尝试消费数据。那么,解决这一问题的方案就是:条件变量。
具体实现如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
typedef struct node
{
int _data;
struct node *_next;
}node_t,* node_p,**node_pp; node_p head = NULL; node_p alloc_node(int data)
{
node_p ret = (node_p)malloc(sizeof(node_t));
ret->_data = data;
ret->_next = NULL;
return ret;
} void init(node_pp phead)
{
*phead = alloc_node();
} void push_front(node_p head,int data)
{
node_p tmp = alloc_node(data);
tmp->_next = head->_next;
head->_next = tmp;
} void pop_front(node_p head, int * pdata)
{
if(head->_next!=NULL)
{
node_p tmp = head->_next;
head->_next = tmp->_next; *pdata = tmp->_data;
free(tmp);
}
} void show(node_p head)
{
node_p cur = head->_next;
while(cur)
{
printf("%d->", cur->_data);
cur = cur->_next;
}
printf("\n");
} //消费者
void * consumer(void *argv)
{
int data;
while()
{
pthread_mutex_lock(&lock);
while(head->_next==NULL)
// if(head->_next==NULL)
{
printf("producter is not ready\n\n");
pthread_cond_wait(&cond,&lock);
break;
}
// else{
// printf("producter is ready...\n");
pop_front(head,&data);
printf("%s data = %d \n",__func__, data);
// }
pthread_mutex_unlock(&lock); sleep();
}
} void * producter(void * argv)
{
int data = rand()%;
while()
{
sleep();
pthread_mutex_lock(&lock);
push_front(head,data);
printf("%s data :: %d\n",__func__, data);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond); //条件变量v操作
}
} int main(int argc, char const *argv[])
{
init(&head); pthread_t id1,id2; pthread_create(&id1,NULL,consumer,NULL);
pthread_create(&id2,NULL,producter,NULL); pthread_join(id1,NULL);
pthread_join(id2,NULL);
}

由图可以看出,这下我们的消费者不再进行过多次没必要的轮寻访问,当生产者生产数据时,告诉消费者可以进行消费了,那么消费者进行消费。
其实这也就是著名的:好莱坞原则---不要打电话给我们,我们会通知你。
eg,在面试笔试中,我们不需要过度的紧张是否被录用,只需要在做到最大努力之后等着招聘方通知就好。
注:一个Condition Variable总是和一个Mutex搭配使用的。一个线程可以调用
pthread_cond_wait在一一个Condition Variable上阻塞等待,这个函数做以下三步操作:
1. 释放Mutex
2. 阻塞等待
3. 当被唤醒时,重新获得Mutex并返回
linux多线程-互斥&条件变量与同步的更多相关文章
- Linux多线程(三)(同步互斥)
1. 线程的同步与互斥 1.1. 线程的互斥 在Posix Thread中定义了一套专门用于线程互斥的mutex函数.mutex是一种简单的加锁的方法来控制对共享资源的存取,这个互斥锁只有两种状态(上 ...
- Linux系统编程—条件变量
条件变量是用来等待线程而不是上锁的,条件变量通常和互斥锁一起使用.条件变量之所以要和互斥锁一起使用,主要是因为互斥锁的一个明显的特点就是它只有两种状态:锁定和非锁定,而条件变量可以通过允许线程阻塞和等 ...
- 27 python 初学(信号量、条件变量、同步条件、队列)
参考博客: www.cnblogs.com/yuanchenqi/articles/5733873.html semaphore 信号量: condition 条件变量: event 同步条件:条件 ...
- OS: 读者写者问题(写者优先+LINUX+多线程+互斥量+代码)(转)
一. 引子 最近想自己写个简单的 WEB SERVER ,为了先练练手,熟悉下在LINUX系统使用基本的进程.线程.互斥等,就拿以前学过的 OS 问题开开刀啦.记得当年学读者写者问题,尤其是写者优先的 ...
- linux中的条件变量
1 大家可能知道互斥量是线程程序中必须的工具了,但是也不能是万能的,就比如某个线程正在等待共享数据某个条件的发生,这个时候会发生什么呢.它就可能重复的尝试对互斥对象锁定和解锁来检查共享数据结构. 2 ...
- POSIX多线程编程-条件变量pthread_cond_t
条件变量通过允许线程阻塞和等待另一个线程发送信号的方法弥补了互斥锁的不足,它常和互斥锁一起使用.使用时,条件变量被用来阻塞一个线程,当条件不满足时,线程往往解开相应的互斥锁并等待条件发生变化.一旦其它 ...
- 【Linux多线程】三个经典同步问题
在了解了<同步与互斥的区别>之后,我们来看看几个经典的线程同步的例子.相信通过具体场景可以让我们学会分析和解决这类线程同步的问题,以便以后应用在实际的项目中. 一.生产者-消费者问题 问题 ...
- Linux Posix线程条件变量
生产者消费者模型 .多个线程操作全局变量n,需要做成临界区(要加锁--线程锁或者信号量) .调用函数pthread_cond_wait(&g_cond,&g_mutex)让这个线程锁在 ...
- Linux 多线程互斥量互斥
同步 同一个进程中的多个线程共享所在进程的内存资源,当多个线程在同一时刻同时访问同一种共享资源时,需要相互协调,以避免出现数据的不一致和覆盖等问题,线程之间的协调和通信的就叫做线程的同步问题, 线程同 ...
随机推荐
- C#使用ICSharpCode.SharpZipLib.dll压缩文件夹和文件
大家可以到http://www.icsharpcode.net/opensource/sharpziplib/ 下载SharpZiplib的最新版本,本文使用的版本为0.86.0.518,支持Zip, ...
- WindowsCE project missing - 转
00x0 前言 之前在Windows 7系统中开发的WindowsCE项目,最近换成Windows 10系统,需要将项目进行修改,打开项目后提示如下错误: 无法读取项目文件“App.csproj”.. ...
- JRE 1.8.0_65/66 Certified with Oracle E-Business Suite
Java Runtime Environment 1.8.0_65 (a.k.a. JRE 8u65-b17) and JRE 1.8.0_66 (8u66-b17) and later update ...
- DMSFrame 之SqlCacheDependency(一)
1.SqlCacheDependency都是我们常用的一种Cache写法了.对后面的SQL 2005算是比较成熟的一种缓存模式了,这里介绍一下DMSFrame的SqlCacheDependency是怎 ...
- easyui+Spring MVC+hibernate = 乐途
这个东西,玩的差不多了;不浪费口水了, 直接上图 发到blog 上让大家看看. 布局各方面有没有不足的地方 .请多多指教 http://item.taobao.com/item.htm?spm=686 ...
- Xenia and Divisors
Xenia and Divisors time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- codeforces D. Design Tutorial: Inverse the Problem
题意:给定一个矩阵,表示每两个节点之间的权值距离,问是否可以对应生成一棵树, 使得这棵树中的任意两点之间的距离和矩阵中的对应两点的距离相等! 思路:我们将给定的矩阵看成是一个图,a 到 b会有多条路径 ...
- 关于鼠标事件的screenY,pageY,clientY,layerY,offsetY属性 (详细图解)
screenY 鼠标相对于显示器屏幕左上角的偏移 pageY 鼠标相对于页面左上角的偏移 (其值不会受滚动条的影响) IE9之下并不支持这个属性 但是可以写点代码计算出来. jQuery中的实现: / ...
- How to implement an algorithm from a scientific paper
Author: Emmanuel Goossaert 翻译 This article is a short guide to implementing an algorithm from a scie ...
- 使用ELK(Elasticsearch + Logstash + Kibana) 搭建日志集中分析平台实践--转载
原文地址:https://wsgzao.github.io/post/elk/ 另外可以参考:https://www.digitalocean.com/community/tutorials/how- ...