---
# System prepended metadata

title: 20240205 python 筆記
tags: [python自學筆記]

---

### #threading:
a flow of execution,each thread takes a turn running to achieve concurrency.


#concurrency:並發性:把一個工作拆分成數個子任務，由不同thread共同完成。
#parallelism:並行性:每個單位獨立完成各自的任務，不相干擾

==========================
用法:
Thread_Name=threading.Thread(target=,arg=())    #arg=()為原func的parameters,tuple

Thread_Name.start()執行此線程

Thread_Name.join() 等待其他線程完成後，才繼續往後執行

==========================
#limitations:
1.CPU bound:task spends most of its time waiting "internal" events(e.g:CPU interprets),have better using "multiprocessing"

2.IO bound:task spends most of its time waiting "external events"(e.g:user inputs,web surfing),have better using "multithreading"
```python
import threading
import time
print(threading.active_count())
print(threading.enumerate())

def Eat_Breakfast():
    time.sleep(3)
    print("ate breakfast")
def Drink_Coffee():
    time.sleep(5)
    print("drank coffee")
def study():
    time.sleep(6)
    print("stdied")

x=threading.Thread(target=Eat_Breakfast,args=())    #args()，如果func 有parameters 可以放入tuple
y=threading.Thread(target=Drink_Coffee,args=())
z=threading.Thread(target=study,args=())

x.start()
y.start()
z.start()

x.join()
y.join()
z.join()

print(threading.active_count()) #現在的thread數量
# Eat_Breakfast()
# Drink_Coffee()
# study()
```
### daemon thread:常駐程式
在使用multiple threads時，其他thread會獨立於main thread進行分工，而main thread的工作完成時，其他thread(non-demon thread)則會在背後繼續運行，如想在main thread完成後讓背後thread也停止運行，就要使用daemon thread的形式。

用法:
Thread_Name=threading.Thread(target=func_Name,daemon=true)
Thread_Name.start()

Thread_Name.setdaemon(True/False)   #daemon on/off
```python
import threading 
import time
def timer():
    ini_time=1
    while True:
        print("time=",ini_time)
        time.sleep(1)
        ini_time+=1


thread_1=threading.Thread(target=timer,args=(),daemon=True)
thread_1.start()


name=input("What's your name?")


#daemon:在輸入之後，timer也會停止計時，反之如果為一般thread，輸入之後仍會一直計時。
#此段要在.py中執行!!!!! C:\Users\a2147\OneDrive\桌面\python\learning python\#thread.py
```
### multiprocessing:多程序
多個任務利用cpu的多核心"並行"，for CPU bound tasks (CPU used heavily)

用法:
Process_Name=Process(target=Name,args=())
```python
from multiprocessing import Process,cpu_count
import time
def counter(num):
    ini=0
    while ini<num:
        ini+=1
def main():
    t0=time.perf_counter()

    a=Process(target=counter,args=(25000000,))
    b=Process(target=counter,args=(25000000,))
    c=Process(target=counter,args=(25000000,))

    a.start()
    b.start()
    c.start()

    a.join()
    b.join()
    c.join()

    t1=time.perf_counter()
    print("spend_time",t1-t0)
if __name__=="__main__":
    main()
    print(cpu_count())

#要在終端機上執行!!!    #C:\Users\a2147\OneDrive\桌面\python\learning python\multiple process.py
#如果process數量超過核心數目，反而會增加工作時間。
```