Golang, Python line Cheng ...

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Growing one small step a day is a big step in the accumulation.

In go, 15 threads are opened, and each thread increments the global variable traverse by 100,000 times, so the predicted result is 15*100000=1500000.

var sum intvar cccc intvar m *sync. Mutexfunc Count1 (i int, ch Chan int) {for   J: = 0; J < 100000; J + + {      CCCC = CCCC + 1   }   ch <-cccc}fu NC Main () {   m = new (sync. Mutex)   ch: = Make (chan int, n) for   I: = 0; i <; i++ {      go Count1 (i, ch)   } for   I: = 0; i < 15 ; i++ {      Select {case      msg: = <-ch:         fmt. PRINTLN (MSG)}}}   

But the final result, 406527

Indicates that a lock needs to be added.

Func Count1 (i int, ch Chan int) {   m.lock () for   J: = 0; J < 100000; J + + {      CCCC = CCCC + 1   }   Ch <-CCCC   m.unlock ()}

Final output: 1500000

Python: Not in the same way.

Count = 0def Sumcount (temp):    global count for    I in range (temp):        count = count + 1li = []for i in range]: 
  th = Threading. Thread (Target=sumcount, args= (1000000,))    Th.start ()    li.append (TH) for i in Li:    i.join () print (count)

Output results: 3004737

The instructions also need to be locked:

Mutex = Threading. Lock () Count = 0def Sumcount (temp):    Global Count    mutex.acquire () for    I in range (temp):        count = count + 1< C11/>mutex.release () Li = []for i in range]:    th = Threading. Thread (Target=sumcount, args= (1000000,))    Th.start ()    li.append (TH) for i in Li:    i.join () print (count)

Output 1500000

OK, lock the small.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.