python Simple Threads and Learning tips of share
- 2020-06-03 07:13:01
- OfStack
There is not enough support for threads in python, but it is said that python has a sufficiently complete asynchronous network framework module, which I hope to learn in the future. Here is a brief summary of threads in python
The threading library can be used to execute any python callable object in a separate thread. Although this module does not have sufficient support for thread-related operations, we were able to use simple threads to handle I/O operations to reduce program response times.
from threading import Thread
import time
def countdown(n):
while n > 0:
print('T-minus:', n)
n -= 1
t = Thread(target=countdown, args=(10,))
t.start() # Open the thread
time.sleep(2)
if t.is_alive() is True:
print(" Stop the thread ...")
t._stop() # Stop the thread
The start function is used to start the thread, and the _stop function is used to stop the thread. To prevent problems such as blocking during I/O operations in a thread, after running for a period of time, you can determine if the thread is still alive and if it still exists, call _stop() to stop it from blocking (you can wrap the _stop function into a class, which I'm not doing here).
Of course, you can call the ThreadPool thread pool to handle this instead of manually creating threads. Using threads is convenient if there is no need to share variables between threads, which can save a lot of trouble and time. If we need to communicate between threads, we can use queues:
from queue import Queue
from threading import Thread
class kill:
def terminate(self, t):
if t.isAlive is True:
t._stop()
def product(out_q):
for i in range(5):
out_q.put(i)
def consumer(in_q):
for i in range(5):
print(in_q.get())
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=product, args=(q,))
t1.start()
t2.start()
k = kill() # Query whether the thread terminates to prevent blocking ...
k.terminate(t1)
k.terminate(t2)
The Queue instance is Shared by all threads, and it has all the required locks, so they can be safely Shared between as many threads as they want. Be careful here not to use methods of the queue class other than the put(),get() methods in multithreaded environments, as this is not reliable! For simple communication of data within small threads, queues can be used for processing. If the data is large and requires interactive communication, python provides modules that you can use, specifically u need baidu.
The so-called coroutines are yield programs in a single-threaded environment.
from collections import deque
def countdown(n):
while n > 0:
print("T-minus", n)
yield # So the next time I go back, I'm going to execute it directly from here ... The equivalent of C# The inside too yield return .
n -= 1
print("this is countdown!!!")
def countup(n):
x = 0
while x < n:
print("Counting up", x)
yield
x += 1
class TaskScheduler:
def __init__(self):
self._task_queue = deque()
def new_task(self, task):
self._task_queue.append(task)
def run(self):
while self._task_queue:
task = self._task_queue.popleft()
try:
next(task)
self._task_queue.append(task)
except StopIteration:
pass
sche = TaskScheduler()
sche.new_task(countdown(10))
sche.new_task(countdown(5))
sche.new_task(countup(15))
sche.run()
Here said under this paragraph of time use python tips, python is really good, but the performance is also unpopular peaces, 1 python started learning, I also do 1 more flattering program, at the very least pretend bility high sound, such as using python sentiment analysis of natural language processing to do as well as the hottest crawlers, and do dazzle chart of data analysis. Gradually, I put those down, because the focus of the program is not on those, as long as you know the basic syntax, understand the official documents can be made, and the focus of the program code is on performance, optimization. Write the program with the most perfect function, the best performance and the most beautiful structure to the greatest extent. In fact, this is just like the "cultural soft power" often said by political teachers. The "soft power" in the program should be the most suitable design mode embedded in the program, the most complete program optimization, and the most efficient data structure.