代码语言:javascript复制
#!/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
代码语言:javascript复制#_*_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 '