This article is participating in Python Theme Month. See the link to the event for more details
Hello, everybody. I found another interesting little thing today. I’m an old poem about funny gadgets.
Recognize multithreading
Multithreading (threading) is a technique that enables multiple threads of software or hardware to execute concurrently. Multithreaded computers have hardware that allows more than one thread to execute at the same time, improving overall processing performance. Systems with this capability include symmetric multiprocessors, multi-core processors, and chip-level multiprocessing or simultaneous multithreading processors. These independently running pieces of a program are called threads, and the concept of programming with them is called multithreading.
Write multithreading
There are two ways to use threads in Python: by wrapping a thread object as a function or as a class.
Functional: Calls start_new_thread() in the Thread module to generate a new thread. The syntax is as follows:
Thread. start_new_thread (function, args[, kwargs]) Parameter description: function – Indicates the thread function. Args – The argument passed to the thread function. It must be of type tuple. Kwargs – This parameter is optional.
#! /usr/bin/python # -* -coding: utf-8 -* -import thread import time # def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % (threadName, time.ctime(time.time())) thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: passCopy the code
Thread-1: Thu Jan 22 15:42:17 2009 thread-1: Thu Jan 22 15:42:19 2009 thread-2: Thu Jan 22 15:42:19 2009 Thu Jan 22 15:42:19 2009 Thread-1: Thu Jan 22 15:42:21 2009 Thread-2: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:25 2009 Thread-2: Thu Jan 22 15:42:27 2009 Thread-2: Thu Jan 22 15:42:31 2009 Thread-2: Thu Jan 22 15:42:35 2009Copy the code
Multithreaded Application Scenarios
When do you need multithreading? We can use multithreading when we don’t want to stop a program from blocking. For example, web crawlers. Of course, a crawler can crawl without multithreading. But what’s the difference between using it and not using it? There are performance bottlenecks without multithreading. If you’re just crawling hundreds or thousands of pieces of data, that’s fine. How about tens of millions of pieces of data? Network requests are blocked and we need to wait for an answer from the network. In this case, a few more threads are much faster than the hardware can support.
For a deeper understanding of multithreading and more source code examples. Please move to the public number: poem-like code.
Now that I’m in, it’s not easy to be original. Let’s go with a “like”.