|
1鱼币
本帖最后由 Boibot 于 2022-10-23 15:54 编辑
- import threading # 线程模块
- import time
- def eat_breakfast():
- time.sleep(3)
- print("You eat breakfast")
- def drink_coffee():
- time.sleep(4)
- print("You drank coffee")
- def study():
- time.sleep(5)
- print("You finish studying")
- x = threading.Thread(target=eat_breakfast, args=()) # 1.target=function,这里的函数加不加括号是一样的吗?
- x.start()
- y = threading.Thread(target=drink_coffee, args=())
- y.start()
- z = threading.Thread(target=study, args=())
- z.start()
- x.join() # thread synchronization(线程同步)
- y.join() # thread synchronize and join(线程同步并加入)
- z.join()
- # eat_breakfast()
- # drink_coffee()
- # study()
- print(threading.active_count()) # 函数名活动计数
- print(threading.enumerate()) # 函数名枚举
- print(time.perf_counter()) # performance counter function(函数名性能计数器)
- console window output: # 2.time.perf_counter()是以秒为单位,我的输出相较正确答案大了上万倍
- You eat breakfast
- You drank coffee
- You finish studying
- 1
- [<_MainThread(MainThread, started 14744)>]
- 9517.6617491
- from multiprocessing import Process, cpu_count
- import time
- def counter(num):
- count = 0
- while count < num:
- count += 1
- def main():
- print(cpu_count())
- a = Process(target=counter, args=(12500000,)) # 3.Process(target=counter, args=(12500000,)),Pruocess函数的args参数是元组,里面的num元素为什么必须要加","逗号
- b = Process(target=counter, args=(12500000,))
- c = Process(target=counter, args=(12500000,))
- d = Process(target=counter, args=(12500000,))
- e = Process(target=counter, args=(12500000,))
- f = Process(target=counter, args=(12500000,))
- g = Process(target=counter, args=(12500000,))
- h = Process(target=counter, args=(12500000,))
- a.start()
- b.start()
- c.start()
- d.start()
- e.start()
- f.start()
- g.start()
- h.start()
- a.join()
- b.join()
- c.join()
- d.join()
- e.join()
- f.join()
- g.join()
- h.join()
- print("Finished in", time.perf_counter(), "seconds")
- if __name__ == '__main__':
- main()
- console window output: # 4.time.perf_counter()是以秒为单位,我的输出相较正确答案大了上万倍
- 16
- Finished in 75426.6729955 seconds
复制代码
|
|