Python simple thread and collaborative learning, python and Collaborative Learning

Source: Internet
Author: User

Python simple thread and collaborative learning, python and Collaborative Learning

The support for threads in python is indeed insufficient. However, it is said that python has a complete Asynchronous Network framework module. I hope I can learn it later. Here I will briefly summarize the threads in python.

The threading library can be used to execute any python callable object in a separate thread. Although this module does not support thread-related operations, we can still use simple threads to process I/O operations to reduce program response time.

From threading import Threadimport timedef countdown (n): while n> 0: print ('t-minus: ', n) n-= 1 T = Thread (target = countdown, args = (10,) t. start () # enable thread time. sleep (2) if t. is_alive () is True: print ("Stop thread... ") t. _ stop () # stop a 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 the thread, you can determine whether the thread is still alive after running for a period of time. If the thread still exists, call _ stop () to stop, prevent blocking (you can encapsulate the _ stop function into the class, which I didn't do here ).

Of course, you can call the ThreadPool thread pool for processing, rather than manually creating a thread. If variables do not need to be shared between threads, It is very convenient to use threads, which can reduce a lot of trouble and save time. If we need to communicate between threads, we can use the queue to implement:

From queue import Queuefrom threading import Threadclass 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 () # Check whether the thread is terminated to prevent blocking... k. terminate (t1) k. terminate (t2)

  

A Queue instance is shared by all threads and has all the required locks. Therefore, it can be securely shared among any number of threads. Note that you should not use the queue class except the put () and get () methods in multiple threads, because this is unreliable in the multi-threaded environment! The queue can be used for data communication in simple small threads. If large data requires interactive communication, you can use python to provide related modules, specific u need baidu.

The so-called coroutine is actually the yield program in a single-threaded environment.

From collections import dequedef countdown (n): while n> 0: print ("T-minus", n) yield # The returned result will be executed directly from here next time... equivalent to yield return in C. n-= 1 print ("this is countdown !!! ") Def countup (n): x = 0 while x <n: print (" Counting up ", x) yield x + = 1 class taskschedeld: 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) Doesn't StopIteration: passsche = TaskScheduler () sche. new_task (countdown (10) sche. new_task (countdown (5) sche. new_task (countup (15) sche. run ()

Here I will talk about my experience in using python during this time. python is really good, but its performance is also criticized. I started to learn python and I am also doing some nice programs, at the very least, it sounds awesome, such as using natural language processing in python for sentiment analysis and the most popular crawler programs, as well as dazzling data analysis charts. Gradually, I put them down, because the focus of the program is not those. As long as you have basic syntax and can understand the official documentation, the focus of the program code is performance, optimized. The program with the most perfect writing function, the best performance, and the best structure is actually a bit like the "cultural soft power" that political teachers often say ", the "soft power" in the program should be the most suitable design mode embedded in the program, the most complete program optimization, the use of the most performance-saving data structure and so on.

Related Article

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.