package main
import (
"fmt"
"runtime"
"sync"
"time"
)
var channel chan string = make(chan string)
var mutex *sync.Mutex = new(sync.Mutex)
func loop1() {
fmt.Println("enters 1")
mutex.Lock()
for i := 0; i < 10; i++ {
fmt.Println(i)
time.Sleep(1 * time.Second)
}
mutex.Unlock()
channel <- "over"
}
func loop2() {
fmt.Println("enters 2")
mutex.Lock()
for i := 0; i < 10; i++ {
fmt.Println(i)
time.Sleep(1 * time.Second)
}
mutex.Unlock()
channel <- "over"
}
func main() {
runtime.GOMAXPROCS(1)
go loop1()
go loop2()
fmt.Println(<-channel)
fmt.Println(<-channel)
}package main
import (
"fmt"
"runtime"
"sync"
"time"
)
var channel chan string = make(chan string)
var mutex *sync.Mutex = new(sync.Mutex)
func loop1() {
fmt.Println("enters 1")
mutex.Lock()
for i := 0; i < 10; i++ {
fmt.Println(i)
time.Sleep(1 * time.Second)
}
mutex.Unlock()
channel <- "over"
}
func loop2() {
fmt.Println("enters 2")
mutex.Lock()
for i := 0; i < 10; i++ {
fmt.Println(i)
time.Sleep(1 * time.Second)
}
mutex.Unlock()
channel <- "over"
}
func main() {
runtime.GOMAXPROCS(1)
go loop1()
go loop2()
fmt.Println(<-channel)
fmt.Println(<-channel)
}
package main
import (
"fmt"
"sync"
"time"
)
var data int = 0
var mutex *sync.Mutex = new(sync.Mutex)
func main() {
for i := 0; i < 1000; i++ {
go func() {
defer mutex.Unlock()
mutex.Lock()
data++
}()
}
time.Sleep(2 * time.Second)
fmt.Printf("%d", data)
}
上述只有上锁才会是1000
虽然说goroutine和一般语言的多线程底层实现有区别,但是在编程的概念模型上,还是要将其思考为并发执行。因为goroutine在线程中执行时会被剥夺。