In python, besides the threading. Thread class, you can call the start_new_thread () function in the thread module to generate a new thread.
Import time, thread <br/> def timer (): <br/> Print ('hello') <br/> def test (): <br/> for I in range (0, 10): <br/> thread. start_new_thread (timer, () <br/> If _ name __= = '_ main _': <br/> test () <br/> time. sleep (10)
Or
Import time, thread <br/> def timer (name = none, group = none): <br/> Print ('name: '+ name +', group: '+ group) <br/> def test (): <br/> for I in range (0, 10): <br/> thread. start_new_thread (timer, ('thread' + STR (I), 'group' + STR (I ))) <br/> If _ name __= = '_ main _': <br/> test () <br/> time. sleep (10)
This is thread. start_new_thread (function, argS [, kwargs]) function prototype. The function parameter is the thread function to be called. The args parameter is the parameter that is passed to your thread function, it must be of the tuple type, and kwargs is an optional parameter. The end of a thread generally ends naturally by the thread function. You can also call thread. Exit () in the thread function to throw systemexit exception to exit the thread.
Next, let's take a look at the lock mechanism in thread.Code:
Code 1
Import time, thread <br/> COUNT = 0 <br/> def test (): <br/> global count </P> <p> for I in range (0, 10000): <br/> count + = 1 </P> <p> for I in range (0, 10): <br/> thread. start_new_thread (test, () <br/> time. sleep (5) <br/> Print count
Code 2
Import time, thread <br/> COUNT = 0 <br/> lock = thread. allocate_lock () <br/> def test (): <br/> global count, lock <br/> lock. acquire () </P> <p> for I in range (0, 10000): <br/> count + = 1 </P> <p> lock. release () <br/> for I in range (0, 10): <br/> thread. start_new_thread (test, () <br/> time. sleep (5) <br/> Print count
The value in code 1 does not use the lock mechanism, so it is a multi-threaded concurrent access to the global count variable, resulting in the final count result is not 10000*10, and because the lock is used in Code 2, this ensures that only one thread can modify the Count value at the same time, so the final result is 10000*10.