码迷,mamicode.com
首页 > 编程语言 > 详细

Python 多线程 threading

时间:2016-09-15 15:13:42      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:python 多线程 threading




#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = ‘gaogd‘

‘‘‘

### 多进程
import threading
import time

def run(num):
    print ‘Hi, I am thread %s..lalala‘ % num
    time.sleep(1)


for i in range(20):
  t = threading.Thread(target=run, args=(i,))
  t.start()


‘‘‘


‘‘‘

##进程启动完20个线程就继续走下去,不等待这20个线程走完就回到住线程
import threading
import time

def run(num):
    global NUM
    time.sleep(1)
    print ‘Hi, I am thread %s..lalala‘ % num
    NUM +=1

NUM = 0
for i in range(20):
  t = threading.Thread(target=run, args=(i,))
  t.start()      ##

#time.sleep(2)
print  ‘------>‘,NUM

‘‘‘


‘‘‘

import threading
import time

def run(num):
    global NUM
    time.sleep(1)
    print ‘Hi, I am thread %s..lalala‘ % num
    NUM +=1

NUM = 0
for i in range(20):
    t = threading.Thread(target=run, args=(i,))
    t.start()
    t.join()      ##等子线程执行完再执行子线程。
print  ‘------>‘,NUM

‘‘‘


‘‘‘
###下面两百个线程时并发执行,但是共享内存有点问题
import threading
import time

def run(num):
    global NUM
    time.sleep(1)
    print ‘Hi, I am thread %s..lalala‘ % num
    NUM +=1

NUM = 0
p_list = []    ##线程列表,追加线程实例 t 到这个列表
for i in range(500):
    t = threading.Thread(target=run, args=(i,))
    t.start()
    p_list.append(t)

for i in p_list:
    t.join()      ##等待线程都执行完再执行这个,但是共享的内存有可能出现问题,所有出现NUM不一定等于500,没有加锁导致的问题,这就涉及安全了
print  ‘------>‘,NUM



‘‘‘

import threading
import time

def run(num):
    global NUM
    time.sleep(1)
    print ‘Hi, I am thread %s..lalala‘ % num
    lock.acquire()  ## 加锁
    NUM +=1
    lock.release()   ##释放锁,如果不释放,那后面的就都改不了数据了

NUM = 0
p_list = []
lock = threading.Lock()     ##生成一把锁
for i in range(500):
    t = threading.Thread(target=run, args=(i,))
    t.start()
    p_list.append(t)

for i in p_list:
    t.join()      ##等待线程都执行完再执行这个,但是共享的内存有可能出现问题,所有出现NUM不一定等于200,没有加锁导致的问题,这就涉及安全了
print  ‘------>‘,NUM


Event

#_*_coding:utf-8_*_
__author__ = ‘jieli‘

import threading,time
import random
def light():
    if not event.isSet():
        event.set() #wait就不阻塞 #绿灯状态
    count = 0
    while True:
        if count < 10:
            print ‘\033[42;1m--green light on---\033[0m‘
        elif count <13:
            print ‘\033[43;1m--yellow light on---\033[0m‘
        elif count <20:
            if event.isSet():
                event.clear() #clear the green light , switch on the red light
            print ‘\033[41;1m--red light on---\033[0m‘
        else:
            count = 0
            event.set() #打开绿灯
        time.sleep(1)
        count +=1
def car(n):
    while 1:
        time.sleep(random.randrange(3))
        if  event.isSet(): #绿灯
            print "car [%s] is running.." % n
        else:# red light
            print "car [%s] is waiting for the red light.." %n
            event.wait()
            print "Green light is on , car %s is running.............." %n



if __name__ == ‘__main__‘:
    event = threading.Event()
    Light = threading.Thread(target=light)
    Light.start()
    for i in range(3):
        t = threading.Thread(target=car,args=(i,))
        t.start()

‘‘‘
Events #

An event is a simple synchronization object;
the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.

event = threading.Event()

# a client thread can wait for the flag to be set
event.wait()

# a server thread can set or reset it
event.set()
event.clear()
If the flag is set, the wait method doesn’t do anything.
If the flag is cleared, wait will block until it becomes set again.
Any number of threads may wait for the same event.
‘‘‘


lock


#_*_coding:utf-8_*_
__author__ = ‘jieli‘
import threading,time
def run(n):
    time.sleep(0.5)
    global  num
    lock.acquire() #申请锁并+锁
    num +=1
    lock.release() #释放锁
if __name__ == ‘__main__‘:
    num = 0
    lock = threading.Lock()
    for i in range(1000):
        t = threading.Thread(target=run,args=(i,))
        t.start()

while threading.active_count() != 1:
    print threading.active_count()
else:
    print ‘----all threads done---‘
    print num



Rlock

#_*_coding:utf-8_*_
__author__ = ‘jieli‘
import threading,time

def run1():
    print "grab the first part data"
    lock.acquire()
    global num
    num +=1
    lock.release()
    return num
def run2():
    print "grab the second part data"
    lock.acquire()
    global  num2
    num2+=1
    lock.release()
    return num2
def run3():
    lock.acquire()
    res = run1()
    print ‘--------between run1 and run2-----‘
    res2 = run2()
    lock.release()
    print res,res2

if __name__ == ‘__main__‘:

    num,num2 = 0,0
    lock = threading.RLock()
    for i in range(10):
        t = threading.Thread(target=run3)
        t.start()

while threading.active_count() != 1:
    print threading.active_count()
else:
    print ‘----all threads done---‘
    print num


semaphore
#_*_coding:utf-8_*_
__author__ = ‘jieli‘
import threading,time

def run(n):
    semaphore.acquire()
    time.sleep(1)
    print "run the thread: %s\n" %n
    semaphore.release()

if __name__ == ‘__main__‘:
    num= 0
    semaphore  = threading.BoundedSemaphore(5)
    for i in range(20):
        t = threading.Thread(target=run,args=(i,))
        t.start()
while threading.active_count() != 1:
    pass #print threading.active_count()
else:
    print ‘----all threads done---‘
    print num


本文出自 “奋斗吧” 博客,请务必保留此出处http://lvnian.blog.51cto.com/7155281/1852917

Python 多线程 threading

标签:python 多线程 threading

原文地址:http://lvnian.blog.51cto.com/7155281/1852917

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!