当前位置:网站首页>7 jours d'apprentissage de la programmation simultanée go 7 jours de programmation simultanée go Language Atomic Atomic Atomic actual Operation contains ABA Problems
7 jours d'apprentissage de la programmation simultanée go 7 jours de programmation simultanée go Language Atomic Atomic Atomic actual Operation contains ABA Problems
2022-06-27 22:25:00 【Big Hammer Love Programming】
Pourquoi le dernier article explique - t - ilAtmoicFonctionnement,Parce queatomicLes opérations sont moins utilisées dans le développement des entreprises,Alors mettez - le à la fin.Mais en termes d'importance,atomicL'opération est le noyau le plus critique.
Catalogue des articles de la série
Table des matières
Un.、Atomic-Introduction aux opérations atomiques
2.、goLanguesAtomic Analyse des sources et opérations sur le terrain
2.1 Atomic Fonctions clés et leur interprétation
2.2 atomic Opérations atomiques simultanées
2.3 Opérations atomiques dans n'importe quelle structure de données
Un.、Atomic-Introduction aux opérations atomiques
Les opérations atomiques n'ont rien à voir avec les atomes. , Le concept d'indivisibilité atomique est principalement emprunté pour souligner que l'opération ne peut être divisée. .
Ce qu'il faut résoudre avec la programmation simultanée, c'est la zone critique. ( Modification des ressources publiques )Questions, Le comportement abstrait de manipulation des données est RAW,WAR,WAW.🥤🥤🥤 Dans le processus de codage spécifique ,C'estRW,InRWEn cours, Il n'y a pas d'autres fils pour cette zone critique. . C'est que cette opération atomique ne peut être effectuée que par un seul fil à la fois. , Il n'y a pas plus d'un thread en même temps pour les opérations atomiques .
En résumé,:
Lorsque vous travaillez avec des atomes , C'est comme s'il était plus étroit aux deux extrémités. , Large ruelle au milieu . Les deux extrémités sont assez étroites pour permettre à un seul fil de passer .
Voilà.:

2.、goLanguesAtomic Analyse des sources et opérations sur le terrain
goLanguesAtmoic Les définitions pertinentes sont mises en œuvre principalement dans les domaines suivants: sync.AtomicDans le sac,Atmoic Primitives de mémoire atomique de bas niveau fournies dans le paquet
Pour réaliser l'algorithme de synchronisation.
2.1 Atomic Fonctions clés et leur interprétation
doc.goLa définition principale estSWAP( Opérations d'échange entre variables )、CAS( Opération d'échange de comparaison de variables )、ADD( Variable atomique plus opération )、LOAD( Opérations de chargement des données pour les variables atomiques )、STORE( Opérations de stockage de variables atomiques ).
Ce qui est relativement compliqué, CASFonctionnement:
Comparer et échanger(compare and swap, CAS), Pour l'échange de données sans interruption dans la programmation multithreadée ,Afin d'éviter l'incohérence des données causée par l'incertitude de l'ordre d'exécution et l'imprévisibilité de l'interruption lors de la réécriture simultanée d'une donnée par plusieurs threads. Cette opération compare les valeurs en mémoire aux données spécifiées,Remplacer les données en mémoire par de nouvelles valeurs lorsque les valeurs sont les mêmes.
Explication du code source :
Comparer les anciennes valeurs avec les adresses en mémoire , Si l'ancienne valeur est égale à l'adresse mémoire, , L'adresse mémoire n'a pas été modifiée , Les adresses peuvent être écrites avec de nouvelles valeurs .
Définition des paramètres d'entrée:
addr *uint64: Adresse des données stockées en mémoire
old:Ancienne valeur
new uint64: Nouvelles valeurs
Définition des rétroparamètres :
swapped (TRUE:Échange réussi,FALSE:Échec de l'échange)
// CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value.
func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)CASOui.ABAQuestions:
ABALe problème, c'est queCAS Un problème commun , Peut être exprimé essentiellement comme suit: :
- ProcessusP1 Une valeur a été lue A
- P1Suspendu(Épuisement de la tranche de temps、Interruption, etc.),ProcessusP2Début de la mise en œuvre
- P2Modifier les valeursAValeur numériqueB, Puis il a été modifié en arrière A
- P1Réveillée, Valeur trouvée après comparaison APas de changement,Poursuite du programme
LogiqueCAS Peut résoudre le problème de conflit de l'échange de données multi - thread , Mais si la valeur stockée en mémoire a été modifiée par un autre thread , Et la valeur modifiée est la même que l'ancienne valeur . Voir les dangers spécifiques pour plus de détails. https://zh.wikipedia.org/zh-cn/%E6%AF%94%E8%BE%83%E5%B9%B6%E4%BA%A4%E6%8D%A2
https://zh.wikipedia.org/zh-cn/%E6%AF%94%E8%BE%83%E5%B9%B6%E4%BA%A4%E6%8D%A2
Source complète:
package atomic
import (
"unsafe"
)
// BUG(rsc): On 386, the 64-bit functions use instructions unavailable before the Pentium MMX.
//
// On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core.
//
// On ARM, 386, and 32-bit MIPS, it is the caller's responsibility
// to arrange for 64-bit alignment of 64-bit words accessed atomically.
// The first word in a variable or in an allocated struct, array, or slice can
// be relied upon to be 64-bit aligned.
// SwapInt32 atomically stores new into *addr and returns the previous *addr value.
func SwapInt32(addr *int32, new int32) (old int32)
// SwapInt64 atomically stores new into *addr and returns the previous *addr value.
func SwapInt64(addr *int64, new int64) (old int64)
// SwapUint32 atomically stores new into *addr and returns the previous *addr value.
func SwapUint32(addr *uint32, new uint32) (old uint32)
// SwapUint64 atomically stores new into *addr and returns the previous *addr value.
func SwapUint64(addr *uint64, new uint64) (old uint64)
// SwapUintptr atomically stores new into *addr and returns the previous *addr value.
func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)
// SwapPointer atomically stores new into *addr and returns the previous *addr value.
func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)
// CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value.
func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
// CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value.
func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
// CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value.
func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)
// CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value.
func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)
// CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value.
func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)
// CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value.
func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
// AddInt32 atomically adds delta to *addr and returns the new value.
func AddInt32(addr *int32, delta int32) (new int32)
// AddUint32 atomically adds delta to *addr and returns the new value.
// To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)).
// In particular, to decrement x, do AddUint32(&x, ^uint32(0)).
func AddUint32(addr *uint32, delta uint32) (new uint32)
// AddInt64 atomically adds delta to *addr and returns the new value.
func AddInt64(addr *int64, delta int64) (new int64)
// AddUint64 atomically adds delta to *addr and returns the new value.
// To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)).
// In particular, to decrement x, do AddUint64(&x, ^uint64(0)).
func AddUint64(addr *uint64, delta uint64) (new uint64)
// AddUintptr atomically adds delta to *addr and returns the new value.
func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
// LoadInt32 atomically loads *addr.
func LoadInt32(addr *int32) (val int32)
// LoadInt64 atomically loads *addr.
func LoadInt64(addr *int64) (val int64)
// LoadUint32 atomically loads *addr.
func LoadUint32(addr *uint32) (val uint32)
// LoadUint64 atomically loads *addr.
func LoadUint64(addr *uint64) (val uint64)
// LoadUintptr atomically loads *addr.
func LoadUintptr(addr *uintptr) (val uintptr)
// LoadPointer atomically loads *addr.
func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
// StoreInt32 atomically stores val into *addr.
func StoreInt32(addr *int32, val int32)
// StoreInt64 atomically stores val into *addr.
func StoreInt64(addr *int64, val int64)
// StoreUint32 atomically stores val into *addr.
func StoreUint32(addr *uint32, val uint32)
// StoreUint64 atomically stores val into *addr.
func StoreUint64(addr *uint64, val uint64)
// StoreUintptr atomically stores val into *addr.
func StoreUintptr(addr *uintptr, val uintptr)
// StorePointer atomically stores val into *addr.
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)

2.1 atomicSur le terrain
atomic C'est facile à utiliser. ,Est d'utiliseratmoc.func Pour compléter l'augmentation correspondante ,Opérations d'affectation.
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var operationNums = int32(10)
atomic.AddInt32(&operationNums,12)
fmt.Printf(" Valeur modifiée :%d\n",atomic.LoadInt32(&operationNums))
}
2.2 atomic Opérations atomiques simultanées
Interprétation: Modifier simultanément les valeurs des variables , Valeur de la variable de lecture simultanée .
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var operationNums = int32(10)
group := sync.WaitGroup{}
group.Add(20)
for i := 0; i < 10; i++ {
go func() {
defer group.Done()
time.Sleep(200*time.Millisecond)
atomic.AddInt32(&operationNums,1)
}()
}
for i := 0; i < 10; i++ {
go func(i int) {
defer group.Done()
time.Sleep(200*time.Millisecond)
fmt.Printf("Thread%d Lire les valeurs modifiées :%d\n",i,atomic.LoadInt32(&operationNums))
}(i)
}
group.Wait()
}
2.3 Opérations atomiques dans n'importe quelle structure de données
AdoptionvarDéclarez unatomic.ValueVariable de type. Effectuer des opérations atomiques sur cette variable .
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var box atomic.Value
fmt.Println("Copy box to box2.")
v1 := [...]int{1, 2, 3}
fmt.Printf("Store %v to box.\n", v1)
box.Store(v1)
fmt.Printf("The value load from box is %v.\n", box.Load())
fmt.Println()
}Résultats de la mise en œuvre:Sans surprise, C'est encore bien fait. .
Copy box to box2.
Store [1 2 3] to box.
The value load from box is [1 2 3].Trois、Résumé
Aujourd'hui, l'introduction principaleatomic Concept et simplicité d'utilisation ,Assez superficiel.Pouratomic Étudiants intéressés par l'application ,Ça pourrait être dansgo Exploration des paquets de code source simultanés liés à la langue .Sous le code source,Pas de secret..Allez, allez!️~
🧧🧧🧧 Merci pour la lecture. ,Faites attention, Garde ça pour toi. ~
![]()
边栏推荐
- [LeetCode]515. Find the maximum value in each tree row
- Crontab scheduled task common commands
- Gbase 8A method for reducing the impact on the system by controlling resource usage through concurrency during node replacement of V8 version
- Go from introduction to actual combat - task cancellation (note)
- 使用sqlite3语句后出现省略号 ... 的解决方法
- [LeetCode]动态规划解分割数组I[Red Fox]
- 渗透学习-靶场篇-pikachu靶场详细攻略(持续更新中-目前只更新sql注入部分)
- OpenSSL programming I: basic concepts
- [LeetCode]161. Edit distance of 1
- CDH集群之YARN性能调优
猜你喜欢

Use Fiddler to simulate weak network test (2g/3g)

Go from introduction to actual combat - task cancellation (note)

Management system itclub (Part 2)

读写分离-Mysql的主从复制

C language programming detailed version (learning note 1) I can't understand it after reading, and I can't help it.

Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager

Management system itclub (Part 1)

深度学习又有新坑了!悉尼大学提出全新跨模态任务,用文本指导图像进行抠图

Codeforces Round #723 (Div. 2)

《7天学会Go并发编程》第7天 go语言并发编程Atomic原子实战操作含ABA问题
随机推荐
[leetcode] dynamic programming solution partition array i[red fox]
【mysql实战】查询语句实战演示
Yarn中RMApp、RMAppAttempt、RMContainer和RMNode状态机及其状态转移
CUDA error:out of memory caused by insufficient video memory of 6G graphics card
Remote invocation of microservices
[LeetCode]186. Flip word II in string
Read write separation master-slave replication of MySQL
Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting
[LeetCode]513. Find the value in the lower left corner of the tree
Solution to the error of VMware tool plug-in installed in Windows 8.1 system
How to do function test well? Are you sure you don't want to know?
Acwing weekly contest 57- digital operation - (thinking + decomposition of prime factor)
登录凭证(cookie+session和Token令牌)
软件缺陷管理——测试人员必会
Codeforces Round #723 (Div. 2)
Acwing week 57 longest continuous subsequence - (binary or tree array)
清华大学教授:软件测试已经走入一个误区——“非代码不可”
xpath
Codeforces Round #716 (Div. 2)
渗透学习-靶场篇-pikachu靶场详细攻略(持续更新中-目前只更新sql注入部分)
