Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1754783
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2016-05-03 15:33:42

上接: http://blog.chinaunix.net/uid-7713641-id-5707052.html

7.  使用queue.Queue() 做数据共享。
主线程往Queue() 写入0-99,开10个线程分别把这些99个数字取出来。最后使用join 对线程做同步。

点击(此处)折叠或打开

  1. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s (%(threadName)-2s) %(message)s',)
  2. def thread_pool2():
  3.     def do_stuff(q):
  4.         while True:
  5.             item=q.get()
  6.             if item is None:
  7.                 break
  8.             logging.debug(item)
  9.             q.task_done()

  10.     q=queue.Queue(maxsize=0)
  11.     num_threads=10

  12.     pool=[threading.Thread(target=do_stuff,args=(q,),daemon=False) for i in range(num_threads)]
  13.     for thread in pool:
  14.         thread.start()

  15.     for x in range(100):
  16.         q.put(x)

  17.     #block until all task are done
  18.     q.join()

  19.     #stop workers
  20.     for i in range(num_threads):
  21.         q.put(None)
  22.     for thread in pool:
  23.         thread.join()

  24. thread_pool2()
8.  简单的消费者/生产者,使用condition, 生产者生产了后通知消费者。传递candition.

点击(此处)折叠或打开

  1. #another way of synchronizing threads is through using a Condition object. Because the Condition uses a Lock, it can be tied to a shared resource.
  2. #This allows threads to wait for the resource to be updated. In this example, the consumer() threads wait() for the Condition to be set before continuing.
  3. #The producer() thread is responsible for setting the condition and notifying the other threads that they can continue
  4. def consumer_producer():
  5.     def consumer(cond):
  6.         #wait for the condition and use the resource
  7.         logging.debug("starting consumer thread")
  8.         t=threading.currentThread()
  9.         with cond:
  10.             cond.wait()
  11.             logging.debug("Resource is available to consume")

  12.   &nban>pause))
  13.             time.sleep(pause)
  14.             c.increment()
  15.         logging.debug("Done")

  16.     counter=Counter()
  17.     for i in range(2):
  18.         t=threading.Thread(target=worker,args=(counter,))
  19.         t.start()

  20.     logging.debug("Waiting for worker threads")
  21.     main_thread=threading.currentThread()
  22.     for t in threading.enumerate():
  23.         if t is not main_thread:
  24.             t.join()
  25.     logging.debug("Counter: {}".format(counter.value))

  26. thread_lock()

10.  两个线程使用Lock来共享数据区。
acquire(blocking=True,timeout=-1): 

Acquire a lock, blocking or non-blocking.

When invoked with the blocking argument set to True (the default), block until the lock is unlocked, then set it to locked and return True.

When invoked with the blocking argument set to False, do not block. If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True.

When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. A timeout argument of -1 specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false.

The return value is True if the lock is acquired successfully, False if not (for example if the timeout expired).

Changed in version 3.2: The timeout parameter is new.

Changed in version 3.2: Lock acquires can now be interrupted by signals on POSIX.

下面这段代码worker 一共获取成功了3次 lock,一共尝试了7次。 

点击(此处)折叠或打开

  1. def who_have_lock():
  2.     def lock_holder(lock):
  3.         logging.debug("starting")
  4.         while True:
  5.             lock.acquire()
  6.             try:
  7.                 logging.debug("Holding")
  8.                 time.sleep(0.5)
  9.             finally:
  10.                 logging.debug("Not holding")
  11.                 lock.release()
  12.             time.sleep(0.5)
  13.         return

  14.     def worker(lock):
  15.         logging.debug("starting")
  16.         num_tries=0
  17.         num_acquires=0
  18.         while num_acquires < 3:
  19.             time.sleep(0.5)
  20.             logging.debug("Trying to acquire")
  21.             have_it=lock.acquire(blocking=True,timeout=0)
  22.             try:
  23.                 num_tries+=1
  24.                 if have_it:
  25.                     logging.debug("Iteration {}: Acquired".format(num_tries))
  26.                     num_acquires+=1
  27.                 else:
  28.                     logging.debug("Iteration {} :Not acquired".format(num_tries))
  29.             finally:
  30.                 if have_it:
  31.                     lock.release()
  32.         logging.debug("Done after {} iterations".format(num_tries))

  33.     lock=threading.Lock()
  34.     holder=threading.Thread(target=lock_holder,args=(lock,),name='LockHolder')
  35.     holder.setDaemon(True)
  36.     holder.start()

  37.     worker=threading.Thread(target=worker,args=(lock,),name="Worker")
  38.     worker.start()

  39. who_have_lock()

11.  semaphore的例子,初始了一个2个semaphore,允许两个线程来访问,第3个,4个的访问的将会被阻塞。直到前面某个线程结束。

点击(此处)折叠或打开

  1. #limiting Concurrrent Access to Resources
  2. #it is useful to allow more than one worker access to a resource at a time, while still limiting the overall number. For example,
  3. #a connection pool might support a fixed number of simultaneous connections, or a network application might support a fixed number of concurrent downloads. A Semaphore is one way to manage those connections

  4. def active_pool():
  5.     class ActivePool:
  6.         def __init__(self):
  7.             super(ActivePool,self).__init__()
  8.             self.active=[]
  9.             self.lock=threading.Lock()

  10.         def makeActive(self,name):
  11.             with self.lock:
  12.                 self.active.append(name)
  13.                 logging.debug("Running: {}".format(self.active))
  14.         def makeInactive(self,name):
  15.             with self.lock:
  16.                 self.active.remove(name)
  17.                 logging.debug("Running {}".format(self.active))

  18.     def worker(s,pool):
  19.         logging.debug("Waiting to join the pool")
  20.         with s:
  21.             name=threading.currentThread().getName()
  22.             pool.makeActive(name)
  23.             time.sleep(0.1)
  24.             pool.makeInactive(name)

  25.     pool=ActivePool()
  26.     s=threading.Semaphore(2)
  27.     for i in range(4):
  28.         t=threading.Thread(target=worker,name=str(i),args=(s,pool))
  29.         t.start()

  30. active_pool()

12 .  线程内部的数据。 

点击(此处)折叠或打开

  1. #Thread-specific Data
  2. #While some resources need to be locked so multiple threads can use them, others need to be protected so that they are hidden
  3. #from view in threads that do not “own” them. The local() function creates an object capable of hiding values from view in separate threads.
  4. def thread_private_data():

  5.     def show_value(data):
  6.         try:
  7.             val=data.value
  8.         except AttributeError as e:
  9.             logging.debug("No value yet")
  10.         else:
  11.             logging.debug("values={}".format(val))

  12.     def worker(data):
  13.         show_value(data)
  14.         data.value=random.randint(1,100)
  15.         show_value(data)

  16.     local_data=threading.local()
  17.     show_value(local_data)
  18.     local_data.value=1000
  19.     show_value(local_data)

  20.     for i in range(2):
  21.         t=threading.Thread(target=worker,args=(local_data,))
  22.         t.start()

  23. thread_private_data()

点击(此处)折叠或打开

  1. #To initialize the settings so all threads start with the same value, use a subclass and set the attributes in __init__().
  2. def thread_private_data2():

  3.     def show_value(data):
  4.         try:
  5.             val=data.value
  6.         except AttributeError as e:
  7.             logging.debug("No value yet")
  8.         else:
  9.             logging.debug("values={}".format(val))

  10.     def worker(data):
  11.         show_value(data)
  12.         data.value=random.randint(1,100)
  13.         show_value(data)

  14.     class MyLocal(threading.local):
  15.         def __init__(self,value):
  16.             logging.debug("Initializing {}".format(self))
  17.             self.value=value

  18.     local_data=MyLocal(1000)
  19.     show_value(local_data)

  20.     for i in range(2):
  21.         t=threading.Thread(target=worker,args=(local_data,))
  22.         t.start()

  23. thread_private_data2()
Bonus: 
Rlock, 可以多次acquire() 

点击(此处)折叠或打开

  1. #re-entrant Locks
  2. #In a situation where separate code from the same thread needs to “re-acquire” the lock, use an RLock instead
  3. #with Lock() the second acquisition fails and would have blocked forever, thus need use lock.acquire(timeout=0)
  4. def re_entrant_locks():
  5.     lock=threading.RLock()
  6.     print("First try {}".format(lock.acquire()))
  7.     print("Second try {}".format(lock.acquire(timeout=0)))
  8.     print("third try {}".format(lock.acquire(timeout=0)))

  9. #re_entrant_locks()




阅读(1042) | 评论(0) | 转发(0) |
0

上一篇:python的set 操作

下一篇:python 多线程示例3

给主人留下些什么吧!~~