黑马程序员技术交流社区

标题: 0420day03- 线程/进程 [打印本页]

作者: Wendy0518    时间: 2019-6-6 13:45
标题: 0420day03- 线程/进程
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")
```






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2