当前位置:网站首页>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. ~
![]()
边栏推荐
- 清华大学教授:软件测试已经走入一个误区——“非代码不可”
- 使用Jmeter进行性能测试的这套步骤,涨薪2次,升职一次
- Dialogue with Qiao Xinyu: the user is the product manager of Wei brand, and zero anxiety defines luxury
- Experience sharing of meituan 20K Software Test Engineers
- 从学生到工程师的蜕变之路
- Conversation Qiao Xinyu: l'utilisateur est le gestionnaire de produits Wei Brand, zéro anxiété définit le luxe
- 二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
- [LeetCode]515. 在每个树行中找最大值
- It smells good. Since I used Charles, Fiddler has been completely uninstalled by me
- [leetcode] dynamic programming solution partition array i[red fox]
猜你喜欢

Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear

Secret script of test case design without leakage -- module test
![[MySQL] database function clearance Tutorial Part 2 (window function topic)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] database function clearance Tutorial Part 2 (window function topic)

Summary of Web testing and app testing by bat testing experts

I think I should start writing my own blog.
![[LeetCode]动态规划解拆分整数I[Silver Fox]](/img/18/8dc8159037ec1262444db8899cde0c.png)
[LeetCode]动态规划解拆分整数I[Silver Fox]
![[leetcode] dynamic programming solution partition array ii[arctic fox]](/img/a1/4644206db3e14c81f9f64e4da046bf.png)
[leetcode] dynamic programming solution partition array ii[arctic fox]

Remote invocation of microservices

使用sqlite3语句后出现省略号 ... 的解决方法
![[LeetCode]动态规划解分割数组I[Red Fox]](/img/b2/df87c3138c28e83a8a58f80b2938b8.png)
[LeetCode]动态规划解分割数组I[Red Fox]
随机推荐
AQS SOS AQS with me
【Redis】零基础十分钟学会Redis
[LeetCode]513. Find the value in the lower left corner of the tree
【mysql实战】查询语句实战演示
Matlab finds the position of a row or column in the matrix
软件测试自动化测试之——接口测试从入门到精通,每天学习一点点
管理系统-ITclub(中)
[LeetCode]30. Concatenate substrings of all words
[MySQL practice] query statement demonstration
Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
Day8 - cloud information project introduction and creation
[LeetCode]508. The most frequent subtree elements and
Login credentials (cookie+session and token token)
Dynamic refresh mapper
渗透学习-靶场篇-pikachu靶场详细攻略(持续更新中-目前只更新sql注入部分)
Conversation Qiao Xinyu: l'utilisateur est le gestionnaire de produits Wei Brand, zéro anxiété définit le luxe
Go from introduction to actual combat - execute only once (note)
Codeforces Round #722 (Div. 2)
The "business and Application Security Development Forum" held by the ICT Institute was re recognized for the security capability of Tianyi cloud
Experience sharing of meituan 20K Software Test Engineers
