Multi-Threaded Notes

Source: Internet
Author: User

import threading import queue import time import random‘‘ ‘ 1 .创建一个 Queue.Queue() 的实例,然后使用数据对它进行填充。 2 .将经过填充数据的实例传递给线程类,后者是通过继承 threading.Thread 的方式创建的。 3 .每次从队列中取出一个项目,并使用该线程中的数据和 run 方法以执行相应的工作。 4 .在完成这项工作之后,使用 queue.task_done() 函数向任务已经完成的队列发送一个信号。 5 .对队列执行 join 操作,实际上意味着等到队列为空,再退出主程序。 ‘‘ ‘class jdThread(threading.Thread):      def __init__(self,index,queue):          threading.Thread.__init__(self)          self.index = index          self.queue = queue     def run(self):          while True:              time.sleep( 1 )              item = self.queue.get()              if item is None:                  break              print( "序号:" ,self.index, "任务" ,item, "完成" )              self.queue.task_done()#task_done方法使得未完成的任务数量- 1 q = queue.Queue( 0 ) ‘‘ ‘ 初始化函数接受一个数字来作为该队列的容量,如果传递的是 一个小于等于 0 的数,那么默认会认为该队列的容量是无限的. ‘‘ ‘ for i in range( 2 ):      jdThread(i,q).start()#两个线程同时完成任务for i in range( 10 ):      q.put(i)#put方法使得未完成的任务数量+ 1


Http://www.2cto.com/kf/201504/395335.html


Synchronous:

  1. from multiprocessing import Process, Lock

  2. def L (lock, num):

  3. Lock.acquire ()

  4. Print "Hello Num:%s" % (Num)

  5. Lock.release ()

  6. if __name__ = = ' __main__ ':

  7. Lock = Lock ()

  8. for Num in range:

  9. Process (Target=l, args= (lock, Num)). Start ()

Http://www.runoob.com/python/python-multithreading.html







Multi-Threaded Notes

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.