Go way to learn the language of concurrent ----- Basic Concepts

Concurrent Overview

Concurrency: usually refers to one or more processes occur simultaneously process
1, the conditions of competition: when two or more operations must be performed in the correct order, and the program does not guarantee the order

var data int
go func(){
	data++
}()
if data == 0{
	fmt.Printf("The data:%d\n",data)
}

This code may have three cases

  • Do not print
  • Print The data: 0
  • Print The data: 1
    so that there's uncertainty, which should be avoided, primarily because the competition is emerging that sequential way of thinking, a race condition is one the most difficult types of concurrency found bug
    2, atoms sex
    if identified as atoms or atomic nature, meant to be an integral or non-interrupted in the operating environment
    context: something in this context is atomic, while in other contexts it is not atomic of the. For example, in the context of an application the operation is atomic, in the context of the operating system and not in the atomicity. I.e. atomic operation may vary depending on the range of the currently defined
    atomic design: the context or scope of the definition of first, followed by consideration of whether the operation is atomic
    indivisible and uninterruptible:
    i ++ operations within the program can be divided into
    - retrieve i value
    - increasing the value of i
    - i the value stored in
    each step are atomic, but the combination may not, depending on the context
data := 0
	w := sync.WaitGroup{}
	for i := 0; i < 100000; i++{
		w.Add(1)
		go func() {
			data++
			w.Done()
		}()
	}
	w.Wait()
	fmt.Println("data:",data)

Print data value is uncertain

3, memory access synchronization
example of data competition:

var data int
go func(){
	data++
}()
if data == 0{
	fmt.Printf("The data:%d\n",data)
} else{
	fmt.Printf("the data:%d\n",data)
}

There will always be a program output, in the case of data output will not compete correct
procedures in three critical region (part exclusive access to shared resources):
- goroutine increase in data variables
- if the checking whether data == 0 founded
- fmt.Printf retrieved and output data values
generally will use locking to synchronize memory access, but the lock mechanism automatically resolve the logical correctness of the data or competition issues, but will also cause performance problems

Guess you like

Origin blog.csdn.net/alvin_666/article/details/90344730