标题:python 3 多线程 实战篇 多线程与锁

-------------------------------------------------------------------------------------------------------------------------------

时间:2018/5/16 18:31:56

-------------------------------------------------------------------------------------------------------------------------------

内容:

直接上手代码


import time
from threading import Thread

#work 里面定义需要多线程执行的内容 一般以数据写入或者网络获取为主 利用cpu的等待空闲执行
def work(name):
    time.    sleep(2) #模拟I/O操作,可以打开一个文件来测试I/O,与sleep是一个效果
    print(name,os.getpid())


t_l=[]
start_time=time.time()

for i in range(50):   #执行50次任务
print('kaishi1')
t=Thread(target=work1,args=(results,)) #耗时大概为2秒  #开启一个线程赋值给t

#t=Process(target=work1,args=(results,)) #耗时大概为25秒,创建进程的开销远高于线程,而且对于I/O密集型,多cpu根本不管用
print('kaishi')
print(t)
t_l.append(t)  #把这个进程放到列表里
t.start()     #进程开始

for t in t_l:
    t.join()  #进程合并
stop_time=time.time()
print('run time is %s' %(stop_time-start_time))

# 开启新线程
thread1.start()
thread2.start()

# 等待所有线程完成
thread1.join()
thread2.join()

print "Exiting Main Thread"

列表不是必须的。

  • 问题二:

使用join是为了阻塞当前线程(即主线程),直到两个子线程结束





import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)



直接上手代码


import time
from threading import Thread

#work 里面定义需要多线程执行的内容 一般以数据写入或者网络获取为主 利用cpu的等待空闲执行
def work(name):
    time.    sleep(2) #模拟I/O操作,可以打开一个文件来测试I/O,与sleep是一个效果
    print(name,os.getpid())


t_l=[]
start_time=time.time()

for i in range(50):   #执行50次任务
print('kaishi1')
t=Thread(target=work1,args=(results,)) #耗时大概为2秒  #开启一个线程赋值给t

#t=Process(target=work1,args=(results,)) #耗时大概为25秒,创建进程的开销远高于线程,而且对于I/O密集型,多cpu根本不管用
print('kaishi')
print(t)
t_l.append(t)  #把这个进程放到列表里
t.start()     #进程开始

for t in t_l:
    t.join()  #进程合并
stop_time=time.time()
print('run time is %s' %(stop_time-start_time))

# 开启新线程
thread1.start()
thread2.start()

# 等待所有线程完成
thread1.join()
thread2.join()

print "Exiting Main Thread"

列表不是必须的。

  • 问题二:

使用join是为了阻塞当前线程(即主线程),直到两个子线程结束





import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)