当前位置:网站首页>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. ~
![]()
边栏推荐
- 北京邮电大学|用于成本和延迟敏感的虚拟网络功能放置和路由的多智能体深度强化学习
- xpath
- Conversation Qiao Xinyu: l'utilisateur est le gestionnaire de produits Wei Brand, zéro anxiété définit le luxe
- It smells good. Since I used Charles, Fiddler has been completely uninstalled by me
- 不外泄的测试用例设计秘籍--模块测试
- 大厂常用软件测试面试题三(附答案)
- 扁平数组和JSON树的转换
- Fill in the blank of rich text test
- 美团20k软件测试工程师的经验分享
- Luogu p5706 redistributing fertilizer and house water
猜你喜欢

對話喬心昱:用戶是魏牌的產品經理,零焦慮定義豪華
![\w和[A-Za-z0-9_],\d和[0-9]等价吗?](/img/96/2649c9cf95b06887b57fd8af2d41c2.png)
\w和[A-Za-z0-9_],\d和[0-9]等价吗?

畅游动态规划之区间DP

Login credentials (cookie+session and token token)

Management system itclub (Part 2)

美团20k软件测试工程师的经验分享

解决本地连接不上虚拟机的问题
![The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)](/img/e6/4eb2ddf4d9bac5e40bf2e96656d294.png)
The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)
![[MySQL] database function clearance Tutorial Part 2 (window function topic)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] database function clearance Tutorial Part 2 (window function topic)

The create database of gbase 8A takes a long time to query and is suspected to be stuck
随机推荐
Gbase 8A method for reducing the impact on the system by controlling resource usage through concurrency during node replacement of V8 version
MONTHS_ Between function use
Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)
使用Fiddler模拟弱网测试(2G/3G)
mysql 大于 小于 等于符号的表示方法
[LeetCode]30. 串联所有单词的子串
[LeetCode]100. 相同的树
二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
Test automatique de Test logiciel - test d'interface de l'introduction à la maîtrise, apprendre un peu chaque jour
Codeforces Round #719 (Div. 3)
C language programming detailed version (learning note 1) I can't understand it after reading, and I can't help it.
gomock mockgen : unknown embedded interface
Professor of Tsinghua University: software testing has gone into a misunderstanding - "code is necessary"
Windwos 8.1系统安装vmware tool插件报错的解决方法
OpenSSL Programming II: building CA
软件缺陷管理——测试人员必会
average-population-of-each-continent
Conversion between flat array and JSON tree
QT base64 encryption and decryption
Interval DP of Changyou dynamic programming
