A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Wendy0518 初级黑马   /  2019-6-6 13:45  /  466 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

0420day03- 线程/进程

线程daemon需要对所有子线程设置daemon= true才能在主线程结束时所有线程终止
The entire Python program exits when no alive non-daemon threads are left.

进程daemon
When a process exits, it attempts to terminate all of its daemonic child processes. processes will be terminated  if non-daemonic processes have exited.



note: cpu boss, process is land,  thread is farmer on the land shaing resources( so thread can't separate from each other and can't be paralle computation), cpu-process-farmer,

order of main process ,child process/ order among child processes 在就绪态都是无序的

#### 线程lock

when lock is created- unlocked
acquire locked
release unlocked

When more than one thread is blocked in [`acquire()`](https://docs.python.org/3.5/library/threading.html#threading.Lock.acquire) waiting for the state to turn to unlocked, only one thread proceeds when a [`release()`](https://docs.python.org/3.5/library/threading.html#threading.Lock.release) call resets the state to unlocked; which one of the waiting threads proceeds vary across implementations. so to make the lock works like join(), which aims to allow only one thread processing at one time, the lock should be coded like below, use lock.acquire() and lock.release() in targeted function definition.

```python
import threading
import time

lock = threading.Lock()

universal = 10

def say(a,b):
    lock.acquire()
    global universal
    # lock.release()
    print(a,b,universal)
    universal +=1
    print(universal, "from subthread1")
    # time.sleep(0.5)
    lock.release()

def record(a):
    lock.acquire()
    global universal
    # lock.acquire()
    list1 = []
    list1.append([a,universal])
    # time.sleep(1)
    print(list1)

    # time.sleep(2)
    universal *= 2
    # time.sleep(2)
    print(universal,"from subthread2")
    # time.sleep(5)
    lock.release()

if __name__ == '__main__':

    # subprocess1 = multiprocessing.Process(target=say,args=(1,2),daemon=0)
    # subprocess2 = multiprocessing.Process(target=record,args=(3,),daemon=0)
    #
    # subprocess1.start()
    # subprocess2.start()
    # # time.sleep(2)
    # print("end")
    subthread1 = threading.Thread(target=say,args=(1,1))
    subthread2 = threading.Thread(target=record,args=(2,))
    # subthread2.start()
    # subthread2.join()
    subthread1.start()
    subthread2.start()
    print("main thread ended")
```

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马