2020-12-09 空间管理

py内存管理

参考:https://realpython.com/python-memory-management/
这个比方很棒

Memory Is an Empty Book

You can begin by thinking of a computer’s memory as an empty book intended for short stories. There’s nothing written on the pages yet. Eventually, different authors will come along. Each author wants some space to write their story in.

Since they aren’t allowed to write over each other, they must be careful about which pages they write in. Before they begin writing, they consult the manager of the book. The manager then decides where in the book they’re allowed to write.

Since this book is around for a long time, many of the stories in it are no longer relevant. When no one reads or references the stories, they are removed to make room for new stories.

In essence, computer memory is like that empty book. In fact, it’s common to call fixed-length contiguous blocks of memory pages, so this analogy holds pretty well.

The authors are like different applications or processes that need to store data in memory. The manager, who decides where the authors can write in the book, plays the role of a memory manager of sorts. The person who removed the old stories to make room for new ones is a garbage collector.

pythonGIl锁

The GIL is a solution to the common problem of dealing with shared resources, like memory in a computer. When two threads try to modify the same resource at the same time, they can step on each other’s toes. The end result can be a garbled mess where neither of the threads ends up with what they wanted.

背景:接着多个作者往一本书中写故事的比方,多个线程就像多个作者,如果都在写一本书,第一,线程没有限制谁先写谁后写(以及是否可以同时写),第二,没有一个明确的限制,不能去别人的页上写。那么会造成,a线程的故事在x页还没写完,b线程就跑进来也在x页上写了,这样导致x页上的故事根本读不了,被两(或多)人你一笔我一笔写的乱七八糟的。GIL解决了第一点提到的问题(一旦有线程执行时,通过锁住解释器,此时解释器只处理一个线程的逻辑,其他人拿不到解释器),即a写的时候,b不可以来写,这样即便页是共享的,至少故事在页上是相对连续的,GIL就是这个作用;那么问题二来了,假设a写完了,交卷(页)了,但是突然发现有个结尾落下了,想回去补上,但是发现b线程已经在x页上面写了一大堆,把a气的只能在b写完的基础上接着写个结尾,这样别人看a的故事没头没尾的了,这就是GIL为何无法解决python线程的问题,但是可以解决进程的(因为进程会被分配一块自己的独有的内存,独享页)。

疑问:那么GIL为何仅能解决线程一半问题就被提出了呢,还是它本身只是为了解决进程的问题 又或者它只是解决线程问题的一个步骤,还没等继续解决后面问题,发现线程问题似乎没法解决了?

你可能感兴趣的:(2020-12-09 空间管理)