总结:1 线程的并发是利用cpu上下文的切换2 线程是最小的调度单位3 python3是假的多线程,它不是真真正正的并行,其实就是串行, 只不过利用了cpu上下文的切换而已4 多线程执行的顺序是无序的5 多线程共享全局变量6 线程是继承在进程里的,没有进程就没有线程7 只要在进行耗时的IO操作的时候,能释放GIL,所以只要在IO密集型的代码里,用多线程就很合适,计算频繁时,不要用多线程多线程执行的顺序是无序的多线程共享全局变量
- import threading
- import time
- def test1(n):
- time.sleep(1)
- print('task-%s'%n)
- for i in range(10):
- t=threading.Thread(target=test1,args=('%s'%i,))
- t.start()
- import threading
- g_num=0
- def update():
- global g_num
- for i in range(10):
- g_num+=1
- def reader():
- print(g_num)
- t1=threading.Thread(target=update)
- t2=threading.Thread(target=reader)
- t1.start()
- t2.start()
- import threading
- import time
- def test1(n):
- time.sleep(1)
- print('task-%s'%n)
- l=[]
- start=time.time()
- for i in range(10):
- t=threading.Thread(target=test1,args=(i,))
- t.start()
- l.append(t)
- for j in l:
- j.join()
- end=time.time()
- print('cost',(end-start))
- import threading
- count=0
- lock=threading.Lock()
- def test1():
- global count
- lock.acquire()
- for i in range(100000):
- count+=1
- lock.release()
- def test2():
- global count
- lock.acquire()
- for i in range(100000):
- count+=1
- lock.release()
- t1=threading.Thread(target=test1)
- t2=threading.Thread(target=test2)
- t1.start()
- t2.start()
- t1.join()
- t2.join()
- print(count)