functhread2(info []string, from chanstring, to chanstring) { deferfunc() { wait <- nil }() for _, send := range info { fmt.Println("Thread 2 Send ", send) to <- send
funcmain() { chan1 := make(chanstring) chan2 := make(chanstring) go thread1([]string{ "I'm doing well, thank you! How about you, Jamhus?", "Well, first I need to finish up some reports for the meeting this afternoon...", "Thanks for offering, but I think I can handle it.", }, chan1, chan2) go thread2([]string{ "Good morning, Mr.Smith! How are you today?", "I'm great, thanks for asking. So, what's on the agenda for today?", "Sounds busy! Do you need any help with the reports?", }, chan2, chan1) <-wait <-wait }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Thread 2 Send Good morning, Mr.Smith! How are you today? Thread 1 Receive Good morning, Mr.Smith! How are you today? Thread 1 Send I'm doing well, thank you! How about you, Jamhus? Thread 2 Receive I'm doing well, thank you! How about you, Jamhus? Thread 2 Send I'm great, thanks for asking. So, what's on the agenda for today? Thread 1 Receive I'm great, thanks for asking. So, what's on the agenda for today? Thread 1 Send Well, first I need to finish up some reports for the meeting this afternoon... Thread 2 Receive Well, first I need to finish up some reports for the meeting this afternoon... Thread 2 Send Sounds busy! Do you need any help with the reports? Thread 1 Receive Sounds busy! Do you need any help with the reports? Thread 1 Send Thanks for offering, but I think I can handle it. Thread 2 Receive Thanks for offering, but I think I can handle it. Thread 2 Finished. Thread 1 Finished.
funcmain() { msg.PushBack(nil) go reciever("Thread1") go sender() go reciever("Thread2") time.Sleep(time.Second) go reciever("Thread3") <-wait <-wait <-wait <-wait }
funcaddWithLock() { for i := 0; i < 2000; i++ { lock.Lock() // 加锁 val++ lock.Unlock() // 解锁 } }
funcaddWithoutLock() { for i := 0; i < 2000; i++ { val++ } }
funcmain() { val = 0 for i := 0; i < 5; i++ { go addWithoutLock() } time.Sleep(time.Second) fmt.Printf("AddWithoutLock: %d\n", val) // AddWithoutLock: 8512
val = 0 for i := 0; i < 5; i++ { go addWithLock() } time.Sleep(time.Second) fmt.Printf("AddWithLock: %d\n", val) // AddWithLock: 10000 }