首页 文章 精选 留言 我的

精选列表

搜索[Rust编程],共10000篇文章
优秀的个人博客,低调大师

Java并发编程专题系列之从底层分析LockSupport原理机制

从底层分析LockSupport原理机制 知识点 LockSupport的介绍 LockSupport类是Java6(JSR166-JUC)引入的一个类,提供了基本的线程同步原语。LockSupport实际上是调用了Unsafe类里的函数,归结到Unsafe里,只有两个函数,而仅仅两个简单的接口,就为上层提供了强大的同步原语,先来解析下两个函数是做什么的。 public native void unpark(Thread jthread); public native void park(boolean isAbsolute, long time); park:阻塞当前线程(Block current thread),字面理解park,就算占住,停车的时候不就把这个车位给占住了么?起这个名字还是很形象的。 isAbsolute参数是指明时间是否属于绝对。 time参数是指时间值 线程调用park函数则等待"许可"。 unpark: 使给定的线程停止阻塞(Unblock the given thread blocked)。 thread参数是指对相应的线程进行解除阻塞。 线程调用unpark函数为线程提供"许可(permit)"。 这个有点像信号量,但是这个"许可"是不能叠加的,"许可"是一次性的。 比如,线程B连续调用了三次unpark函数,当线程A调用park函数就使用掉这个"许可",如果线程A再次调用park,则进入等待状态。 注意,unpark函数可以先于park调用。比如线程B调用unpark函数,给线程A发了一个"许可",那么当线程A调用park时,它发现已经有"许可"了,那么它会马上再继续运行。(此部分比wait/notify(notifyAll))要好很多。 park和unpark的灵活之处 unpark函数可以先于park调用,这个正是它们的灵活之处。 一个线程它有可能在别的线程unPark之前,或者之后,或者同时调用了park,那么因为park的特性,它可以不用担心自己的park的时序问题,否则,如果park必须要在unpark之前。 考虑一下,两个线程同步,要如何处理? 在Java5里是用wait/notify/notifyAll来同步的。wait/notify机制有个很蛋疼的地方是,比如线程B要用notify通知线程A,那么线程B要确保线程A已经在wait调用上等待了,否则线程A可能永远都在等待。 另外,是调用notify,还是notifyAll? notify只会唤醒一个线程,如果错误地有两个线程在同一个对象上wait等待,那么又悲剧了。为了安全起见,貌似只能调用notifyAll了。 park/unpark模型真正解耦了线程之间的同步,线程之间不再需要一个Object或者其它变量来存储状态,不再需要关心对方的状态。 拓展延伸 HotSpot里park/unpark的实现,每个java线程都有一个Parker实例,Parker类是这样定义的: class Parker : public os::PlatformParker { private: volatile int _counter ; ... public: void park(bool isAbsolute, jlong time); void unpark(); ... } class PlatformParker : public CHeapObj<mtInternal> { protected: pthread_mutex_t _mutex [1] ; pthread_cond_t _cond [1] ; ... } 可以看到Parker类实际上用Posix的mutex,condition来实现的。 在Parker类里的_counter字段,就是用来记录所谓的“许可”的。 当调用park时,先尝试直接能否直接拿到"许可",即_counter>0时,如果成功,则把_counter设置为0,并返回:(和信号量的思路很像!) void Parker::park(bool isAbsolute, jlong time) { // Ideally we'd do something useful while spinning, such // as calling unpackTime(). // Optional fast-path check: // Return immediately if a permit is available. // We depend on Atomic::xchg() having full barrier semantics // since we are doing a lock-free update to _counter. if (Atomic::xchg(0, &_counter) > 0) return; 如果不成功,则构造一个ThreadBlockInVM,然后检查_counter是不是>0,如果是,则把_counter设置为0,unlock mutex并返回: ThreadBlockInVM tbivm(jt); if (_counter > 0) { // no wait needed _counter = 0; status = pthread_mutex_unlock(_mutex); 否则,再判断等待的时间,然后再调用pthread_cond_wait函数等待,如果等待返回,则把_counter设置为0,unlock mutex并返回: if (time == 0) { status = pthread_cond_wait (_cond, _mutex) ; } _counter = 0 ; status = pthread_mutex_unlock(_mutex) ; assert_status(status == 0, status, "invariant") ; OrderAccess::fence(); 当unpark时,则简单多了,直接设置_counter为1,再unlock mutext返回。如果_counter之前的值是0,则还要调用pthread_cond_signal唤醒在park中等待的线程: void Parker::unpark() { int s, status ; status = pthread_mutex_lock(_mutex); assert (status == 0, "invariant") ; s = _counter; _counter = 1; if (s < 1) { if (WorkAroundNPTLTimedWaitHang) { status = pthread_cond_signal (_cond) ; assert (status == 0, "invariant") ; status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant") ; } else { status = pthread_mutex_unlock(_mutex); assert (status == 0, "invariant") ; status = pthread_cond_signal (_cond) ; assert (status == 0, "invariant") ; } } else { pthread_mutex_unlock(_mutex); assert (status == 0, "invariant") ; } } 用mutex和condition保护了一个_counter的变量,当park时,这个变量置为了0,当unpark时,这个变量置为1。 值得注意的是在park函数里,调用pthread_cond_wait时,并没有用while来判断,所以posix condition里的"Spurious wakeup"一样会传递到上层Java的代码里。 if (time == 0) { status = pthread_cond_wait (_cond, _mutex) ; } 这也就是为什么Java dos里提到,当下面三种情况下park函数会返回: Some other thread invokes unpark with the current thread as the target; or Some other thread interrupts the current thread; or The call spuriously (that is, for no reason) returns. 相关的实现代码在: http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/share/vm/runtime/park.hpp http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/share/vm/runtime/park.cpp http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/os/linux/vm/os_linux.hpp http://hg.openjdk.java.net/build-infra/jdk7/hotspot/file/52c4a1ae6adc/src/os/linux/vm/os_linux.cpp 其它的一些东东: Parker类在分配内存时,使用了一个技巧,重载了new函数来实现了cache line对齐。 // We use placement-new to force ParkEvent instances to be // aligned on 256-byte address boundaries. This ensures that the least // significant byte of a ParkEvent address is always 0. void * operator new (size_t sz) ; Parker里使用了一个无锁的队列在分配释放Parker实例: volatile int Parker::ListLock = 0 ; Parker * volatile Parker::FreeList = NULL ; Parker * Parker::Allocate (JavaThread * t) { guarantee (t != NULL, "invariant") ; Parker * p ; // Start by trying to recycle an existing but unassociated // Parker from the global free list. for (;;) { p = FreeList ; if (p == NULL) break ; // 1: Detach // Tantamount to p = Swap (&FreeList, NULL) if (Atomic::cmpxchg_ptr (NULL, &FreeList, p) != p) { continue ; } // We've detached the list. The list in-hand is now // local to this thread. This thread can operate on the // list without risk of interference from other threads. // 2: Extract -- pop the 1st element from the list. Parker * List = p->FreeNext ; if (List == NULL) break ; for (;;) { // 3: Try to reattach the residual list guarantee (List != NULL, "invariant") ; Parker * Arv = (Parker *) Atomic::cmpxchg_ptr (List, &FreeList, NULL) ; if (Arv == NULL) break ; // New nodes arrived. Try to detach the recent arrivals. if (Atomic::cmpxchg_ptr (NULL, &FreeList, Arv) != Arv) { continue ; } guarantee (Arv != NULL, "invariant") ; // 4: Merge Arv into List Parker * Tail = List ; while (Tail->FreeNext != NULL) Tail = Tail->FreeNext ; Tail->FreeNext = Arv ; } break ; } if (p != NULL) { guarantee (p->AssociatedWith == NULL, "invariant") ; } else { // Do this the hard way -- materialize a new Parker.. // In rare cases an allocating thread might detach // a long list -- installing null into FreeList --and // then stall. Another thread calling Allocate() would see // FreeList == null and then invoke the ctor. In this case we // end up with more Parkers in circulation than we need, but // the race is rare and the outcome is benign. // Ideally, the # of extant Parkers is equal to the // maximum # of threads that existed at any one time. // Because of the race mentioned above, segments of the // freelist can be transiently inaccessible. At worst // we may end up with the # of Parkers in circulation // slightly above the ideal. p = new Parker() ; } p->AssociatedWith = t ; // Associate p with t p->FreeNext = NULL ; return p ; } void Parker::Release (Parker * p) { if (p == NULL) return ; guarantee (p->AssociatedWith != NULL, "invariant") ; guarantee (p->FreeNext == NULL , "invariant") ; p->AssociatedWith = NULL ; for (;;) { // Push p onto FreeList Parker * List = FreeList ; p->FreeNext = List ; if (Atomic::cmpxchg_ptr (p, &FreeList, List) == List) break ; } }

优秀的个人博客,低调大师

Java并发编程专题系列之深入分析synchronized(基础篇)

synchronized同步关键字简介 synchronized是属于JVM层面的一个关键字,底层是通过一个monitor对象(管程对象)来完成,由于wait()/notify()等方法也依赖于monitor对象,所以只有在同步的块或者方法中才能调用wait/notify等方法 synchronized同步代码块底层实现 synchronized同步语句块的实现使用monitorenter和 monitorexit 指令。 monitorenter:指令指向同步代码块的开始位置 monitorexit:指令则指明同步代码块的结束位置 synchronized获取锁 当执行monitorenter指令时,当前线程将试图获取objectref(即对象锁) 所对应的 monitor的持有权,当 objectref的monitor 的进入计数器**为0,那线程可以成功取得 monitor,并将计数器值设置为 1,取锁成功。 如果当前线程已经拥有 objectref 的 monitor 的持有权,那它可以重入这个 monitor (关于重入性稍后会分析),重入时计数器的值也会加 1。 倘若其他线程已经拥有objectref 的 monitor 的所有权,那当前线程将被阻塞,直到正在执行线程执行完毕,即monitorexit指令被执行,执行线程将释放monitor(锁)并设置计数器值为0,其他线程将有机会持有 monitor ;** 为了保证在方法异常完成时 monitorenter 和 monitorexit 指令依然可以正确配对执行,编译器会自动产生一个异常处理器,这个异常处理器声明可处理所有的异常,它的目的就是用来执行 monitorexit 指令。 从字节码中也可以看出多了一个monitorexit指令,它就是异常结束时被执行的释放monitor的指令; monitorenter(进入管程对象) 每个对象有一个管程对象(monitor),当monitor被占用时就会处于锁定状态;线程执行monitorenter指令时尝试获取monitor的所有权,过程如下: 如果monitor的进入计数器为0,则该线程进入monitor,然后将进入计数器设置为1,该线程即为monitor的所有者; 如果线程已经之前占用了该monitor,本次只是重新进入,则将monitor的进入计数器加1; 如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入计数器为0,再重新尝试获取monitor的所有权; monitorexit(退出管程对象) 执行monitorexit的线程必须是objectref(即对象锁)所对应的monitor的所有者; 指令执行时,monitor的进入计数器减1,如果减1后进入计数器为0,那线程退出monitor,不再是这个monitor的所有者。其他被这个monitor阻塞的线程可以尝试去获取这个 monitor 的所有权. 同步方法中synchronized底层实现 方法级的同步是隐式,即无需通过字节码指令(monitorenter和monitorexit)来控制的。 它实现在方法调用和返回操作之中。 JVM可以从方法常量池中的方法表结构(method_info Structure) 中的ACC_SYNCHRONIZED访问标志区分一个方法是否同步方法。 当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,如果设置了,执行线程将先持有monitor(虚拟机规范中用的是管程一词)。 然后再执行方法,最后在方法完成(无论是正常完成还是非正常完成)时释放monitor。 在方法执行期间,执行线程持有了monitor,其他任何线程都无法再获得同一个monitor。如果一个同步方法执行期间抛出了异常,并且在方法内部无法处理此异常,那这个同步方法所持有的monitor将在异常抛到同步方法之外时自动释放。

优秀的个人博客,低调大师

木兰编程语言重现:匿名函数,lambda 表达式初步

之前实现了基本的函数功能,本周支持了如下的 lambda 表达式: 边长 -> 边长 * 边长 用->似乎符合数学中“映射”的表示(下摘自 wiki “Lambda calculus”页): 可以在 map、filter 中使用: print(list(map(边长 -> 边长 * 边长, [1, 2, 3]))) => [1, 4, 9] 也可以在块中包含多个语句: print(list(map(边长 -> { 面积 = 边长 * 边长 return 面积 }, [1, 2, 3]))) 如果这些语句较短(中文命名的标识符往往更短),也可以用分号分隔后放在一行内: print(list(map(边长 -> { 面积 = 边长 * 边长; return 面积 }, [1, 2, 3]))) 暂时只添加了单个形参的 lambda 表达式,还有些用法仍在摸索。 还有一种类似功能的匿名函数写法: print(list(map(func (边长) { 面积 = 边长 * 边长; return 面积 }, [1, 2, 3]))) 它已经支持多形参,也可以在调用时直接跟实参: print(func (长, 宽) { 面积 = 长 * 宽; return 面积 }(3, 4)) => 12 代码统计 下面是几个主要部分的代码行数统计,格式为:上周->本周。 测试 木兰测试用例:1075 -> 1090 运行测试.py,检验所有木兰测试代码片段:145 -> 148 未变 test语法树.py,确保生成的语法树与原始版本一致:63 实现:1941 -> 2075 分析器/语法分析器.py:824 -> 886 分析器/语法树.py,功用/调试辅助.py,包括对 ast 库的中文封装:260 -> 271 分析器/词法分析器.py:184 -> 187 环境.py,加载木兰模块:87 -> 88 未变 演示高亮.py:98 中.py,主程序:35

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码