并发编程:几个关键概念和三个经典问题

【AI概念】迁移学习 vs. 域自适应 vs. 域泛化|定义、核心原理、数学表达、易混淆点与工程选择建议|实际案例、工程实现细节、未来研究趋势、实际应用场景 大家好,我是爱酱。本篇将会详细梳理迁移学习(Transfer Learning)、域自适应(Domain Adaptation)、域泛化(Domain Generalization)三大常被混淆的核心概念,结合数学公式、典型算法与实际应用场景,帮助你厘清它们的本质区别、联系与工程意义。 注:本文章含大量数学算式、详细例子说明及大量代码演示,大量干货,建议先收藏再慢慢观看理解。新频道发展不易,你们的每个赞、收藏跟转发都是我继续分享的动力! 阅读详情

几个关键概念

Race Condition

A race condition or race hazard is a flaw in an electronic system or process whereby the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events. The term originates with the idea of two signals racing each other to influence the output first

Critical section

In concurrent programming a critical section is a piece of code that accesses a shared resource (data structure or device) that must not be concurrently accessed by more than one thread of execution. A critical section will usually terminate in fixed time, and a thread, task or process will have to wait a fixed time to enter it (aka bounded waiting). Some synchronization mechanism is required at the entry and exit of the critical section to ensure exclusive use, for example a semaphore.

Mutex
Hardware solutions

On a uniprocessor system a common way to achieve mutual exclusion inside kernels is to disable interrupts for the smallest possible number of instructions that will prevent corruption of the shared data structure, the critical section. This prevents interrupt code from running in the critical section, that also protects against interrupt-based process-change.

In a computer in which several processors share memory, an indivisible test-and-set of a flag could be used in a tight loop to wait until the other processor clears the flag. The test-and-set performs both operations without releasing the memory bus to another processor. When the code leaves the critical section, it clears the flag. This is called a "spinlock" or "busy-wait".

Similar atomic multiple-operation instructions, e.g., compare-and-swap, are commonly used for lock-free manipulation of linked lists and other data structures.

Software solutions

Beside the hardware supported solution, some software solutions exist that use "busy-wait" to achieve the goal. Examples of these include the following:

Unfortunately, spin locks and busy waiting are wasteful of processor time and power and are considered anti-patterns in almost every case. In addition, these algorithms do not work if Out-of-order execution is utilized on the platform that executes them. Programmers have to specify strict ordering on the memory operations within a thread.

The solution to these problems is to use synchronization facilities provided by an operating system's multithreading library, which will take advantage of hardware solutions if possible but will use software solutions if no hardware solutions exist. For example, when the operating system's lock library is used and a thread tries to acquire an already acquired lock, the operating system will suspend the thread using a context switch and swaps it out with another thread that is ready to be run, or could put that processor into a low power state if there is no other thread that can be run. Therefore, most modern mutual exclusion methods attempt to reduce latency and busy-waits by using queuing and context switches. However, if the time that is spent suspending a thread and then restoring it can be proven to be always more than the time that must be waited for a thread to become ready to run after being blocked in a particular situation, then spinlocks are a fine solution for that situation only.

Advanced mutual exclusion

Synchronization primitives can be built like the examples below by using the solutions explained above:

 

Lock

In computer science, a lock is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution.

Locks typically require hardware support for efficient implementation. This usually takes the form of one or more atomic instructions such as "test-and-set", "fetch-and-add" or "compare-and-swap". These instructions allow a single process to test if the lock is free, and if free, acquire the lock in a single atomic operation.

The reason an atomic operation is required is because of concurrency, where more than one task executes the same logic. For example, consider the following C code:

if (lock == 0) lock = myPID; /* lock free - set it */

The above example does not guarantee that the task has the lock, since more than one task can be testing the lock at the same time. Since both tasks will detect that the lock is free, both tasks will attempt to set the lock, not knowing that the other task is also setting the lock. Dekker's or Peterson's algorithm are possible substitutes if atomic locking operations are not available.

Semaphore

In computer science, a semaphore is a protected variable or abstract data type that constitutes a classic method of controlling access by several processes to a common resource in a parallel programming environment. A semaphore generally takes one of two forms: binary and counting. A binary semaphore is a simple "true/false" (locked/unlocked) flag that controls access to a single resource. A counting semaphore is a counter for a set of available resources. Either semaphore type may be employed to prevent a race condition. On the other hand, a semaphore is of no value in preventing resource deadlock, such as illustrated by the dining philosophers problem.

Counting semaphores are accessed using operations similar to the following Pascal examples. Procedure V will increment the semaphore S, whereas procedure P will decrement it:

 procedure V (S : Semaphore);
 begin
   (* Atomic operation: increment the semaphore. *)
   S := S + 1;
 end;
 
   (* Atomic operation: decrement the semaphore. *)
 procedure P (S : Semaphore);
 begin
   (* Whole operation is atomic *)
   repeat
     Wait();
   until S > 0;
   S := S - 1;
 end;

To guarantee that two or more processes do not attempt to simultaneously modify the same semaphore, the operations that actually increment or decrement the semaphore are designated as atomic, meaning they cannot be interrupted, such as by preemption. This requirement may be met by using a machine instruction that is able to read, modify and write the semaphore in a single operation. In the absence of such a hardware instruction, an atomic operation may be synthesized by temporarily suspending preemption or, less desirably, by temporarily disabling hardware interrupts.

Semaphores remain in common use in programming languages that do not intrinsically support other forms of synchronization. They are the primitive synchronization mechanism in many operating systems. The trend in programming language development, though, is towards more structured forms of synchronization, such as monitors (though these advanced structures typically employ semaphores behind the scenes). In addition to their inadequacies in dealing with (multi-resource) deadlocks, semaphores do not protect the programmer from the easy mistakes of taking a semaphore that is already held by the same process, and forgetting to release a semaphore that has been taken.

A mutex is a binary semaphore that usually incorporates extra features, such as ownership, priority inversion protection or recursivity. The differences between mutexes and semaphores are that semaphores are operating system dependent, though mutexes are implemented by specialized and faster routines. Mutexes are meant to be used for mutual exclusion (post/release operation is restricted to thread that called pend/acquire) only and binary semaphores are meant to be used for event notification (post-ability from any thread) and mutual exclusion.

Events are also sometimes called event semaphores and are used for event notification.

Monitor

In concurrent programming, a monitor is an object intended to be used safely by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion. That is, at each point in time, at most one thread may be executing any of its methods.

Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task. Monitors also have a mechanism for signaling other threads that such conditions have been met.

For many applications, mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true. A busy waiting loop

   while not( P ) do skip

will not work, as mutual exclusion will prevent any other thread from entering the monitor to make the condition true.

The solution is condition variables. Conceptually a condition variable is a queue of threads, associated with a monitor, upon which a thread may wait for some assertion to become true. Thus each condition variable c is associated with some assertion Pc. While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor's state. In most types of monitors, these other threads may signal the condition variable c to indicate that assertion Pc is true.

Thus there are two main operations on condition variables:

  • wait c is called by a thread that needs to wait until the assertion Pc is true before proceeding. While the thread is waiting, it does not occupy the monitor.
  • signal c (sometimes written as notify c) is called by a thread to indicate that the assertion Pc is true.

As an example, consider a monitor that implements a semaphore. There are methods to increment (V) and to decrement (P) a private integer s. However, the integer must never be decremented below 0; thus a thread that tries to decrement must wait until the integer is positive. We use a condition variable sIsPositive with an associated assertion of PsIsPositive = (s > 0).

monitor class Semaphore {
  private int s := 0
  invariant s >= 0 
  private Condition sIsPositive /* associated with s > 0 */
  
  public method P()
  {
    if s = 0 then wait sIsPositive 
    assert s > 0
    s := s - 1
  }
  
  public method V() {
    s := s + 1
    assert s > 0
    signal sIsPositive 
  }
}

When a signal happens on a condition that at least one other thread is waiting on, there are at least two threads that could then occupy the monitor: the thread that signals and any one of the threads that is waiting. In order that at most one thread occupies the monitor at each time, a choice must be made. Two schools of thought exist on how best to resolve this choice. This leads to two kinds of condition variables which will be examined next:

  • Blocking condition variables give priority to a signaled thread.
  • Nonblocking condition variables give priority to the signaling thread.

http://www.artima.com/insidejvm/ed2/threadsynch.html

http://msdn.microsoft.com/en-us/library/ms173179%28VS.80%29.aspx

http://cseweb.ucsd.edu/classes/fa05/cse120/lectures/120-l6.pdf

http://www.cs.mtu.edu/~shene/NSF-3/e-Book/SEMA/TM-example-buffer.html

http://www.cs.mtu.edu/~shene/NSF-3/e-Book/MONITOR/ProducerConsumer-1/MON-example-buffer-1.html

三个经典问题

Producer-Consumer Problem

信号量版本

 

 

Monitor 版本

 

 

Note the use of while statements in the above code, both when testing if the buffer is full or empty. With multiple consumers, there is a race condition where one consumer gets notified that an item has been put into the buffer but another consumer is already waiting on the monitor so removes it from the buffer instead. If the while was instead an if too many items may be put into the buffer or a remove might be attempted on an empty buffer.

 

java 版本 (ArrayBlockingQueue)

 

 

可以被中断的lock,被中断后将signal progagate 到其他thread

 

尝试性质的操作

poll()  -   offer(E)

poll(long, TimeUnit) - offer(E, long, TimeUtil)

 

wait知道成功的操作

take() - put(E)

 

throw exception的操作

add(E) - remove(E)

 

java wait 指定时间的版本

 

 

 

Reader-Writer Problem

信号量版本

  • 首先要有读者计数和写着计数,readCnt, writeCnt
  • 相应的需要两个mutex semaphore来保护这个变量的修改, m1, m2
  • 需要两个信号量w, r 进行读者和写者之间的同步(wait和唤醒)
    • 第一个读者,则w.p,写者无法进入
    • 最后一个读者,则w.v,唤醒可能的写者
    • 第一个写者,则r.p,所有之后的读者无法进入
    • 最后一个写者,则r.v,唤醒可能的读者
    • 写者之间互斥
  • 最后,还需要一个mutex semaphore来保证只有一个读者被写者wait,等待写者的通知。后来的读者读者被该读者wait,等待该读者的通知。因为写者之前已经互斥,所以最多只有一个写者被读者wait,等待读者的通知,后来的写者被该写者wait,等待该写者的通知。

 

 

 

信号量版本2

去掉写者计数器和保护mutex

合并w,r,mutex3为一个w_or_r互斥量

 

 

Monitor 版本

 

 

Java 版本

understanding java read-write lock 1

understanding java read-write lock 2

 

 

jdk1.5实现用采用lock free

 

 

 

 

 

 

http://cs.gmu.edu/cne/modules/ipc/orange/readmon.html


Dining philosophers problem

 

 

如何使用freesurfer对T1w结构像进行分区指标的提取?——皮层面积,灰质体积,平均厚度,厚度标准差,平均曲率、高斯曲率、曲率指数、折叠指数 阅读详情

相关推荐

保姆级教程:在RK3576上配置USB网卡从零到外网访问(附udev规则详解)

本文提供了在RK3576开发板上配置USB网卡的完整教程,涵盖从内核驱动、udev规则到网络路由的全流程。重点讲解了如何利用USB Gadget功能实现高速网络连接,并构建稳定的算力集群,确保多设备间通信及外网访问。

grass的博客 465

Cannot lock Java compile cache (xxx)as it has already been locked by this process 解决办法

Execution failed for task ':compileJava'. > Could not create service of type DefaultGeneralCompileCaches using GradleScopeCompileServices.createGeneralCompileCaches(). > Cannot lock Java compile cache (C:\Devin\code2\global-adapter\source\.gradle\6.9.1\

Java修炼记 5174

温度实时检测预警系统(STC89C51RC+DS18B20)

温度实时检测预警系统

1 兴趣 2 实践 1500

人工智能导论——机器学习的基本概念

1、基本概念:训练集,测试集,特征值,监督学习,非监督学习,半监督学习,分裂,回归 2、概念学习:人类学习概念(婴儿):鸟,狗;车,房子;黑匣子和计算机 定义:概念学习是指从有关某个布尔函数(是或否)的输入输出训练样例中推断出该布尔函数 3、决定小明是否享受运动 c(x)=1,当享受运动时;c(x)=0当不享受运动时,c(x)也可作为y x:每一个实例(每一行数据6个属性的值) X:样例,所有实例的集合 学习目标:f:X->Y 4、训练集/训练样例:用来进行训练,也就是产生模型或者算法的数据集 测试集

wang_chao118的博客 1606

C#与发那科机器人通信实战:从SDK配置到机械臂控制

本文详细介绍了如何使用C#与发那科机器人进行通信,从SDK配置到机械臂控制的完整实战流程。内容包括环境准备、通信连接建立、机械臂运动控制、异常处理与状态监控,以及高级功能实战,帮助开发者快速掌握工业机器人编程技术。

weixin_42524276的博客 462

Windows 10 下 Nacos 3.0.2 单机版保姆级安装教程(含JDK 17配置与MySQL 8.0连接避坑)

本文提供Windows 10下Nacos 3.0.2单机版的详细安装教程,涵盖JDK 17配置、MySQL 8.0连接优化及生产级安全设置。通过步骤详解和常见问题解决方案,帮助开发者快速完成Nacos的安装与配置,确保服务发现与配置管理的高效运行。

weixin_29237635的博客 324

习题笔记 Exams/2014 q3fsm

【代码】习题笔记 Exams/2014 q3fsm。

Zephyr_R的博客 174

《低功耗方法学》翻译——卷首语

低功耗设计方法学。

记录所学,分享知识,结识挚友 997

人工智能导论——概念篇

简简单单概况人工智能的情况-对应人工智能专业硕士考试

脑瓜子嗡嗡的小刘 2431

【微服务】SpringBoot 4.0 新特性整合项目实战应用详解

SpringBoot 4.0 新特性整合项目实战应用详解

congge 4599

三菱FX5U系列PLC与汇川IT6000系列触摸屏进行MODBUS TCP通信的具体方法

三菱FX5U系列PLC与汇川IT6000系列触摸屏进行MODBUS TCP通信的具体方法

Robot_PLC_HMI_Automation 6528

Producer-consumer problem in Python

from:http://agiliq.com/blog/2013/10/producer-consumer-problem-in-python/ By :Akshar Raaj We will solve Producer Consumer problem in Python using Python threads. This problem is nowhere as ...

dianxiang0791的博客 390

AI应用架构师视角:AI技术引发的全球经济格局重构,你看懂了吗?

本文将从AI应用架构师的独特视角,拆解AI技术栈(算力/算法/数据)如何通过"架构渗透"重塑产业价值链,分析中美欧等主要经济体的AI战略差异如何改写全球分工格局,并为企业与个人提供一套可落地的"AI经济适应性框架"。当OpenAI的GPT-4在代码生成、多模态理解上展现出超越人类的能力,当英伟达的H100芯片成为全球科技巨头争抢的"数字石油",当中国的AI大模型在电商、金融等场景实现规模化落地——我们正站在一场由AI技术引发的全球经济重构的临界点上。AI重构全球经济格局的过程,既是挑战,更是机遇。

小白菜的博客 1261

【高并发】要想学好并发编程,关键是要理解这三个核心问题

写在前面 写【高并发专题】有一段时间了,一些读者朋友留言说,并发编程很难,学习了很多的知识,但是在实际工作中却无从下手。对于一个线上产生的并发问题,又不知产生这个问题的原因究竟是什么。对于并发编程,感觉上似乎是掌握了,但是真正用起来却不是那么回事! 其实,造成这种现象的本质原因就是没有透彻的理解并发编程的精髓,而学好并发编程的关键是需要弄懂三个核心问题:分工、同步和互斥。 分工 比较官方的解释为...

冰河的专栏 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

96、Python并发编程:三个核心概念及Python并发编程模型

本文简单介绍了程序到执行的一个大概的过程,辨析了程序、进程、线程的概念,同时简单介绍了Python中的并发编程模型。

南宫理的日知录 1400

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

并发编程中的三个概念

并发编程中的三个概念 在并发编程中,我们通常会遇到以下三个问题:原子性问题,可见性问题,有序性问题。我们先看具体看一下这三个概念: 1.原子性 原子性:即一个操作或者多个操作 要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行。 一个很经典的例子就是银行账户转账问题: 比如从账户A向账户B转1000元,那么必然包括2个操作:从账户A减去1000元,往账户B加

qq25910561的博客 1164

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

并发编程的三个重要概念

文章目录前言一、并发编程的三个重要概念是什么?二、概念引入1.cpu的缓存解析2.cpu如何解决缓存不一致问题二、并发编程的三个概念1.原子性1.可见性3.有序性四、如何保证原子性、可见性、有序性。1.原子性2.可见性3.有序性 前言 想要学好并发编程,那么久要完全掌握并发编程的相关概念,接下来我们将一起探讨并发编程中的三个重要概念 提示:以下是本篇文章正文内容,下面案例可供参考 一、并发编程的三个重要概念是什么? 1、原子性 2、可见性 3、有序性 二、概念引入 1.cpu的缓存解析 为了更好的理解并

madleep的博客 509

《菜鸟读并发》并发编程三个核心问题和三个主要BUG源头你知多少?

并发编程的第一原则,那就是不要写并发程序,所以编写正确的并发程序是一件极困难的事情,但要快速而又精准地解决“并发”类的疑难杂症,就要理解这件事情的本质,追本溯源,深入分析这些Bug的源头在哪里。 并发编程三个核心问题和三个主要BUG源头,思维导图如下: 前戏 我们知道我们的的CPU、内存、I/O设备都在不断快速的迭代,不断朝着更快的方向努力。但是,在这个快速发展的过程中,有一个核心矛盾一直存...

qq_25843323的博客 3万+

学好并发编程,关键是要理解这三个核心问题

前言 一些读者朋友留言说,并发编程很难,学习了很多的知识,但是在实际工作中却无从下手。对于一个线上产生的并发问题,又不知产生这个问题的原因究竟是什么。对于并发编程,感觉上似乎是掌握了,但是真正用起来却不是那么回事! 其实,造成这种现象的本质原因就是没有透彻的理解并发编程的精髓,而学好并发编程的关键是需要弄懂三个核心问题:分工、同步和互斥。 分工 比较官方的解释为:分工就是将一个比较大的任务,拆分成多个大小合适的任务,交给合适的线程去完成,强调的是性能。 如果你还不能够理解什么是分工,这里,我们可以做一个

m0_58479800的博客 163

学并发编程,透彻理解这三个核心是关键

写在前面 上一篇文章这次走进并发的世界,请不要错过 给大家带了并发编程的开胃菜,接下来我们逐步上正餐,在吃正餐之前,我还要引用那首诗词: 「横看成岭侧成峰,远近高低各不同」,远看看轮廓,近看看细节,不断切换思维或视角来学习 远看并发,并发编程可以抽象成三个核心问题: 分工、同步/协作、互斥 如果你已经工作了,那么你一定听说过或者正在应用敏捷开发模式来交付日常的工作任务,我们就用你熟悉的流程来解释...

日拱一兵 2521

Java并发编程:volatile关键字解析

Java并发编程:volatile关键字解析    volatile这个关键字可能很多朋友都听说过,或许也都用过。在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果。在Java 5之后,volatile关键字才得以重获生机。   volatile关键字虽然从字面上理解起来比较简单,但是要用好不是一件容易的事情。由于volatile关键字是与Java的内存模

u011396148的博客 1754

9.并发编程的三个概念(原子性、可见性和有序性)存在的问题及其解决方案

以下是本文的目录大纲:一.内存模型的相关概念二.并发编程中的三个概念三.Java内存模型一.内存模型的相关概念大家都知道,计算机在执行程序时,每条指令都是在CPU中执行的,而执行指令过程中,势必涉及到数据的读取和写入。由于程序运行过程中的临时数据是存放在主存(物理内存)当中的,这时就存在一个问题,由于CPU执行速度很快,而从内存读取数据和向内存写入数据的过程跟CPU执行指令的速度比起来要慢的多,因...

郑学炜的技术博客 3785

学好并发编程必须要理解的三个核心问题

一些读者朋友留言说,并发编程很难,学习了很多的知识,但是在实际工作中却无从下手。对于一个线上产生的并发问题,又不知产生这个问题的原因究竟是什么。对于并发编程,感觉上似乎是掌握了,但是真正用起来却不是那么回事! 其实,造成这种现象的本质原因就是没有透彻的理解并发编程的精髓,而学好并发编程的关键是需要弄懂三个核心问题:分工、同步和互斥 需要更多Java知识点和面试题的朋友可以点一点下方链接免费领取 链接:1103806531暗号:CSDN 分工 比较官方的解释为:分工就是将一个比较大的任务,拆分成多个大

XingXing_Java的博客 4372

原创|《菜鸟读并发》并发编程三个核心问题和三个主要BUG源头

点击上方“码农进阶之路”,选择“设为星标”回复“面经”获取面试资料并发编程三个核心问题和三个主要BUG源头,思维导图如下:并发编程的第一原则,那就是不要写并发程序,所以编写正确的并发程序...

二师兄撒欢之地 1万+

Java并发编程:JMM和volatile关键字

一、Java内存模型   随着计算机的CPU的飞速发展,CPU的运算能力已经远远超出了从主内存(运行内存)中读取的数据的能力,为了解决这个问题,CPU厂商设计出了CPU内置高速缓存区。高速缓存区的加入使得CPU在运算的过程中直接从高速缓存区读取数据,在一定程度上解决了性能的问题。但也引起了另外一个问题,在CPU多核的情况下,每个处理器都有自己的缓存区,数据如何保持一致性。为了保证多核处理器的数据一...

TuT 5434

java并发编程中的三个概念

java并发编程中的三个概念

hfbin的博客 584
上一篇: 老调重弹 Composition versus Inheritance
下一篇: Cassandra 源码解析汇总
FireCoder
博客等级 码龄17年 65粉丝 100原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FireCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址