In Python, in addition to being able to implement multithreading by inheriting the Threading.thread class, you can also invoke the Start_new_thread () function in the thread module to produce a new thread, as follows
Import time, Thread def timer (): Print (' hello ') def test (): To I in range (0): Thread.start_new_thread (Timer, ()) If _ _name__== ' __main__ ': Test () Time.sleep (10)
Or
Import time, Thread def timer (Name=none, Group=none): Print (' name: ' + name + ', Group: ' + Group ') def Test (): For I in RA Nge (0): Thread.start_new_thread (Timer, (' thread ' + str (i), ' group ' + str (i)) if __name__== ' __main__ ': Test () Time.sle EP (10)
This is the Thread.start_new_thread (Function,args[,kwargs]) function prototype, where the function argument is the thread that you want to call; args is the argument that passes to your thread function, he must be a tuple type , and Kwargs is an optional parameter. The end of a thread generally relies on the natural end of the thread function, or it can be called thread.exit () in a thread function, and he throws Systemexit exception to exit the thread.
Let's take a look at the lock mechanism in thread, as follows two pieces of code:
Code A
Import time, thread count = 0 def test (): Global count of I in range (0, 10000): Count + = 1 for i in range (0): Thread. Start_new_thread (Test, ()) Time.sleep (5) Print count
Code two
Import time, thread count = 0 lock = thread.allocate_lock () def test (): Global count, lock Lock.acquire () to I in range (0 , 10000): Count = 1 lock.release () for I in range (0): Thread.start_new_thread (Test, ()) Time.sleep (5) Print count
The value in code one does not use the lock mechanism, so multithreading simultaneously accesses the global count variable, causing the final count result to be not 10000*10, and in code two the lock is used to ensure that only one thread at a time can modify the value of count. So the end result is 10000*10.