9 multi-threaded to unshared data

Source: Internet
Author: User

1.g_num is not a global variable
 fromThreadingImportThreadImport Timedeftest1 (): G_num= 100G_num+ = 1Print("---1test1--g_num=%d"%g_num) Time.sleep (2)deftest2 (): Time.sleep (1)    Print("---2test2--g_num=%d"%g_num) T1= Thread (target=test1) T1.start () T2= Thread (target=test2) T2.start ()

## # Results---1test1--g_num=101ExceptioninchThread Thread-2: Traceback (most recent): File"/usr/lib/python3.5/threading.py", line 914,inch_bootstrap_inner self.run () File"/usr/lib/python3.5/threading.py", Line 862,inchRun Self._target (*self._args, * *Self._kwargs) File"10-multithreading-non-shared data. PY", Line 12,inchtest2Print("---2test2--g_num=%d"%g_num) Nameerror:name'G_num'  is  notDefined

2. Thread Name
Import Threadingin [2]: Threading.current_thread () out[2]: <_mainthread (Mainthread, started 139965328148224) > in[3]: Threading.current_thread (). nameout['mainthread '

3. Two threads executing the same function
    • Two threads do not have a relationship with the function
    • Function The individual is personal, the variables inside the function are not related

 fromThreadingImportThreadImportThreadingImport Timedeftest1 (): Name=Threading.current_thread (). NamePrint("---The thread is%s--"%name) G_num= 100ifName = ="Thread-1": G_num+ = 1Print("---%s--g_num=%d"%(name,g_num))Else: Time.sleep (2)        Print("----%s--g_num=%d"%(name,g_num)) T1= Thread (target=test1) T1.start () T2= Thread (target=test1) T2.start ()

    

Small summary
    • In multithreaded development, global variables are data shared by multiple threads, while local variables, such as their own, are non-shared

9 multi-threaded to unshared data

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.