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