Multi-thread instance tutorial in python and python instance tutorial

Source: Internet
Author: User

Multi-thread instance tutorial in python and python instance tutorial

This article describes in detail the usage of multiple threads in Python in the form of examples. It is widely used in Python programming. Share it with you for your reference. The specific analysis is as follows:

The thread and threading modules can be used for multi-thread operations in python. The thread module has been renamed as _ thread in Py3 and is no longer recommended. The threading module is encapsulated on the thread and is also a Recommended multi-threaded module. This article mainly introduces the threading module. In some versions, the thread module may not exist. Use dump_threading to replace the threading module.

I. Thread Creation

Every Thread in the threading module is a Thread object. There are two ways to create a Thread: one is to pass the function to the Thread object for execution, and the other is to inherit from the Thread, then rewrite the run method (not similar to Java ).

The following two methods are used to create a thread and execute simultaneously.

import random, threadingdef threadFunction():  for i in range(10):    print 'ThreadFuction - %d'%i    time.sleep(random.randrange(0,2))class ThreadClass(threading.Thread):  def __init__(self):    threading.Thread.__init__(self);      def run(self):    for i in range(10):      print 'ThreadClass - %d'%i      time.sleep(random.randrange(0,2))if __name__ == '__main__':  tFunc = threading.Thread(target = threadFunction);  tCls = ThreadClass()  tFunc.start()  tCls.start()

The execution result is as follows. We can see that the two threads are printing alternately. As for the empty rows and multiple outputs in one row, the print of Py is NOT thread-safe. After the print of the current thread prints part of the content, before preparing to print the line feed, it is preemptible by the print in other threads, and other content is printed before the line feed.

ThreadFuction - 0ThreadFuction - 1ThreadFuction - 2ThreadClass - 0ThreadFuction - 3ThreadClass - 1ThreadFuction - 4ThreadClass - 2ThreadClass - 3ThreadClass - 4ThreadFuction - 5ThreadClass - 5ThreadClass - 6ThreadClass - 7ThreadClass - 8ThreadFuction - 6ThreadClass - 9ThreadFuction - 7ThreadFuction - 8ThreadFuction - 9

The constructor of the Thread class is defined as follows:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

Group: reserved for ThreadGroup extension. Generally, it is useless.
Target: The task function name of the new thread.
Name: Specifies the thread name, which is generally useless.
Args: tuple Parameter
Kwargs: dictionary Parameter

The member variables and functions of the Thread class are as follows:

Start () starts a thread
The run () thread execution body is also the content to be rewritten.
Join ([timeout]) waits for the end of the thread
Name thread name
Ident thread ID
Daemon
Whether the isAlive () and is_alive () threads are alive
GetName (), setName () Name get & set Method
Get & set Method of isDaemon () and setDaemon () daemon

Here, the daemon thread is not a concept with the daemon process in Linux. This means that the main program will exit after all the daemon threads exit. Otherwise, even if the thread task is not finished, it will exit with the main program as long as it is not the daemon thread. In Linux, the definition of a daemon is the opposite. The daemon has been removed from the parent process and does not exit with the completion of the parent process.

Ii. Thread Synchronization

Thread Synchronization is a core issue in multithreading. The threading module supports thread synchronization well, including thread-specific data, semaphores, mutex locks, and condition variables.

1. Thread-specific data

In short, the thread-specific data is the global variable held by the thread alone, and mutual modification will not affect each other.

The threading module uses the local () method to generate a thread independent object. For example, sleep (1) is used to ensure that the sub-thread runs before running the following statement.

data = threading.local()def threadFunction():  global data  data.x = 3  print threading.currentThread(), data.x  if __name__ == '__main__':  data.x = 1  tFunc = threading.Thread(target = threadFunction).start();  time.sleep(1)  print threading.current_thread(), data.x
<Thread(Thread-1, started 36208)> 3<_MainThread(MainThread, started 35888)> 1

The above output shows that the modification to data. x in Thread-1 does not affect the value of data. x in the main Thread.

2. mutex lock

Two types of locks are defined in threading: threading. Lock and threading. RLock. The difference between the two lies in that the latter is reentrant locks, that is to say, repeating locks in a thread will not cause deadlocks, this is the same as PTHREAD_MUTEX_RECURSIVE in POSIX, that is, recursive locks.

The mutex lock API is very simple. There are only three functions: allocate locks, lock, and unlock.

Threading. Lock () allocates a mutex Lock.
Acquire ([blocking = 1]) locks (blocking or non-blocking. If it is not blocked, it is equivalent to try_lock. If it is returned, False indicates that it has been locked by other threads .)
Release () Unlock
The following example illustrates the use of mutex lock. In the previous example, multi-threaded print may cause chaotic output. Here, a mutex lock is used to ensure that each line must have only one output.

def threadFunction(arg):  while True:    lock.acquire()    print 'ThreadFuction - %d'%arg    lock.release()if __name__ == '__main__':  lock = threading.Lock()  threading.Thread(target = threadFunction, args=(1,)).start();  threading.Thread(target = threadFunction, args=(2,)).start();

3. Condition Variables

Conditional variables are always used together with mutex locks. The conditional variables in threading are bound to an RLock by default. You can also import a custom lock when initializing the conditional variables.

The available functions are as follows:

Threading. condition ([lock]) allocates a Condition variable acquire (* args) Condition variable lock release () Condition variable unlock wait ([timeout]) waiting to wake up, timeout indicates timeout of running y (n = 1) to wake up a maximum of n waiting threads, including yyall () and notify_all () wake up all the waiting threads. The following example uses a condition variable to control two threads to run num = 0def threadFunction (arg): global num while num <10: cond. acquire () while num % 2! = Arg: cond. wait () print 'thread % d-% d' % (arg, num) num + = 1 cond. notify () cond. release () if _ name _ = '_ main _': cond = threading. condition () threading. thread (target = threadFunction, args = (0 ,)). start (); threading. thread (target = threadFunction, args = (1 ,)). start ();

Output:

Thread 0 - 0Thread 1 - 1Thread 0 - 2Thread 1 - 3Thread 0 - 4Thread 1 - 5Thread 0 - 6Thread 1 - 7Thread 0 - 8Thread 1 - 9Thread 0 - 10

In fact, there is a problem with the above program. What we want to print is 0 ~ 9, but in fact 10 is also printed out, the reason is very simple, because the two threads alternate printing, so that num in a thread may add 2, resulting in 10 is printed out, therefore, check again before printing.

I believe this article provides some reference for everyone's Python program design.


Multithreading in python

You do not need to write this. Ready-made in python. You only need to reload ThreadingServer and SocketServer. You can view the example code in python help, or go to site-packages to view the source code.

This is probably the case.
Soc = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Soc. bind (....)
While True:
Client = soc. listen (1)
Start_thread (function_thread, (client ,))
Def function_thread (client ):
Buf = client. recv ()
....

What is the problem with this small example of python multithreading?

It should be because your variable name and class name are the same that the program cannot tell whether your sellThread is a class or a variable.

Change your variable name.

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.