Golang and python thread details and simple examples, golangpython thread

Source: Internet
Author: User

Golang and python thread details and simple examples, golangpython thread

Golang and python thread details and simple examples

In GO, 15 threads are enabled, and each thread increases global variable traversal by 100000 times. Therefore, the prediction 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}func main() {  m = new(sync.Mutex)  ch := make(chan int, 15)  for i := 0; i < 15; i++ {   go Count1(i, ch)  }  for i := 0; i < 15; i++ {   select {   case msg := <-ch:     fmt.Println(msg)   }  }}

But the final result is 406527.

The lock is required.

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

In python: implementation in the same way does not work.

count = 0def sumCount(temp):  global count  for i in range(temp):    count = count + 1li = []for i in range(15):  th = threading.Thread(target=sumCount, args=(1000000,))  th.start()  li.append(th)for i in li:  i.join()print(count)

Output result: 3004737

It also requires locking:

mutex = threading.Lock()count = 0def sumCount(temp):  global count  mutex.acquire()  for i in range(temp):    count = count + 1  mutex.release()li = []for i in range(15):  th = threading.Thread(target=sumCount, args=(1000000,))  th.start()  li.append(th)for i in li:  i.join()print(count)

1500000 output

OK, the lock column.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

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.