这样学 Python 多线程与进程(一)
import time
def exe_time(func):
def new_func(*args, **args2):
t0 = time.time()
print("@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__))
back = func(*args, **args2)
print("@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__))
print("@%.3fs taken for {%s}" % (time.time() - t0, func.__name__))
return back
return new_func
@exe_time
def func1():
time.sleep(1)
print('执行方法1')
time.sleep(2)
@exe_time
def func2():
time.sleep(1)
print('执行方法2')
time.sleep(2)
if __name__ == "__main__":
func1()
func2()
import threading
import time
class thread1(threading.Thread):
def run(self):
# IO操作1
pass
class thread2(threading.Thread):
def run(self):
# IO操作2
pass
if __name__ == '__main__':
t1 = thread1()
t2 = thread2()
t1.start()
t2.start()
import threading
global_value = 0
# 线程锁
thread_lock = threading.Lock()
def add_value():
# 全局变量
global global_value
# 上锁
gLock.acquire()
# 修改全局变量的操作
pass
# 释放锁
gLock.release()
if __name__ == '__main__':
# 定义两个线程,同时去调用一个方法去改变全局变量的值
thread1 = threading.Thread(target=add_value)
thread2 = threading.Thread(target=add_value)
thread1.start()
thread2.start()