一、(LINUX 线程同步) 引入
发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,原创水平有限有误请指出线程相比进程有着先天的数据共享的优势,如下图,线程共享了进程除栈区以外的所有内存区域如下图所示:但是这种共享有时候也会带来问题,简单的考虑如下C++代码:点击(此处)折叠或打开{
千家信息网最后更新 2024年09月22日一、(LINUX 线程同步) 引入原创水平有限有误请指出
线程相比进程有着先天的数据共享的优势,如下图,线程共享了进程除栈区以外的所有内存区域如下图所示:
但是这种共享有时候也会带来问题,简单的考虑如下C++代码:
就是临界区代码
后面将对他们进行描述,这里我们简单实用静态互斥锁进行解决这个问题。
临界区的选择应该尽量小,避免对多线程的并发性产生较大的性能影响
具体代码如下:
注意:一个简单类型的i++也不一定是一个原子操作,所以在涉及到并发修改共享变量的时候一定要使用
线程同步手段。
作者微信:
线程相比进程有着先天的数据共享的优势,如下图,线程共享了进程除栈区以外的所有内存区域如下图所示:
但是这种共享有时候也会带来问题,简单的考虑如下C++代码:
点击(此处)折叠或打开
- {
- int b = 0;
- b = a;
- a = b+1;
- return *this;
- }
就是临界区代码
后面将对他们进行描述,这里我们简单实用静态互斥锁进行解决这个问题。
点击(此处)折叠或打开
- //原子操作 加锁
- pthread_mutex_lock(&mtx);
- ++test;
- pthread_mutex_unlock(&mtx);
- //原子操作 解锁
- cout<<pthread_self() <<":";
- test.prit()
临界区的选择应该尽量小,避免对多线程的并发性产生较大的性能影响
具体代码如下:
点击(此处)折叠或打开
- /*************************************************************************
- > File Name: error.cpp
- > Author: gaopeng QQ:22389860 all right reserved
- > Mail: gaopp_200217@163.com
- > Created Time: Mon 15 May 2017 12:01:33 AM CST
- ************************************************************************/
- #include<iostream>
- #include <pthread.h>
- #include <string.h>
- #define MAXOUT 1000000
- using namespace std;
- static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
- class testc
- {
- private:
- int a;
- public:
- testc()
- {
- a = 1;
- }
- testc& operator++()
- {
- int b = 0;
- b = a;
- a = b+1;
- return *this;
- }
- void prit()
- {
- cout<<a<<endl;
- }
- };
- testc test = test;
- void* testp(void* arg)
- {
- int i = MAXOUT;
- while(i--)
- {
- //原子操作 加锁
- pthread_mutex_lock(&mtx);
- ++test;
- pthread_mutex_unlock(&mtx);
- //原子操作 解锁
- cout<<pthread_self() <<":";
- test.prit();
- }
- }
- int main(void)
- {
- pthread_t tid[3];
- int er;
- int i = 0;
- while(i<3)
- {
- if ((er = pthread_create(tid+i,NULL,testp,NULL) )!=0 )
- {
- strerror(er);
- return -1;
- }
- i++;
- }
- i = 0;
- while(i<3)
- {
- pthread_join(*(tid+i),NULL);
- i++;
- }
- cout<<"last numer: ";
- test.prit();
- }
注意:一个简单类型的i++也不一定是一个原子操作,所以在涉及到并发修改共享变量的时候一定要使用
线程同步手段。
作者微信:
原子
线程
代码
就是
进程
问题
同步
实用
较大
优势
作者
先天
内存
区域
变量
实际
实际上
将对
性能
手段
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
数据库触发器如何调测
门诊查询软件开发风险分析
上海方便网络技术客户至上
sql数据库如何修改时间
三星vpn服务器地址
运行数据库合集
网络安全体验服务
多租户的数据库设计
pq med数据库
数据库测试链接
中国互联网科技大事件
天基互联网科技股
魔兽怀旧服怎么更改服务器地址
公司软件开发目的
sql数据库显示正在恢复
山西软件开发品质保障
西安来实慧网络技术有限公司
戴尔服务器信号传输
黑魂3的 捏脸数据库
云顶之弈显示连接不上服务器
服务器的备份问题
社交网络数据库结构
服务器发挥什么作用是什么
网络安全员招聘要求
数据库技术20世纪
css属于什么服务器
用数据库语言求和1到10
鞍山新零售软件开发价格
access数据库的安装
考辅警网络安全员有什么条件