进程和线程的区别
什么是线程安全
一个线程的修改被另一个线程的修改覆盖掉。
python中哪些操作是线程安全的
线程同步的方式
进程间的通信方式 (IPC:Inter-Process Communication 进程间传递信号或者数据)
多线程的例子
# python实现多线程import threadinglock = threading.Lock()n = [0]def foo(): with lock: # 加锁 n[0] = n[0] + 1 n[0] = n[0] + 1threads = [] # 用来储存所有线程for i in range(5000): t = threading.Thread(target=foo) # 传入foo函数 threads.append(t)for t in threads: t.start()print(n)
多进程的例子
python有GIL,可以用多进程实现cpu密集程序
# 多进程import multiprocessingdef fib(n): if n<= 1: return 1 return fib(n-1) + fib(n-2)if __name__ == '__main__': jobs = [] for i in range(10,20): p = multiprocessing.Process(target=fib, args=(i,)) jobs.append(p) p.start()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。
新闻热点
疑难解答
图片精选