Multi-line Cheng of Python multithreaded programming

Source: Internet
Author: User
Tags php language

The Python language itself supports multithreading , unlike the PHP language.

The following example is a number of threads doing the same task , the task is always task_num, each time the thread does a task (print), and then continue to take the task until all tasks are completed.

1 #Coding:utf-82 ImportThreading3 4Start_task =05Task_num = 100006Mu = threading. Lock ()## #通过工厂方法获取一个新的锁对象7 8 classMyThread (Threading. Thread):## #类MyThread继承基类threading. Thread9 Ten     defRun (self):##线程启动的入口函数, subclasses need to be rewritten One         GlobalStart_task A         Globalmu -         GlobalStart_task -  the          whileStart_task < task_num:##如果任务没有完成, Continue -             ifMu.acquire ():##加锁 -                 ifStart_task <Task_num: -                     PrintStart_task +Start_task = Start_task + 1 -Mu.release ()##释放锁 +  A defTest (): atThread_all = [] -      forIinchRange (6):##for循环创建6个线程 -t = MyThread ()##创建线程 - thread_all.append (t) -T.start ()## #启动线程 -  in      forIinchRange (6): -Thread_all[i].join ()##等待线程结束 to  + if __name__=="__main__": -Test ()

test locking with no lock effect : Set the number of tasks to 10 million or higher, and save the print output separately on multicore machines to illustrate the problem.

Multi-line Cheng of Python multithreaded programming

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.