Solve the problem that the UDT memory is not available, and solve the udt memory
When a simple network communication program is compiled using the UDT library, a problem is found. After some connections are closed, the memory usage of the program remains unchanged. For example, connect 500 first, then connect to another 500, first turn off the next 500, the program occupies half of the memory, then turn off 500, and the program occupies 0.1 of the memory. However, if you first turn off the first 500, the memory usage of the program will not change. The program memory will be reduced to 500 only when the next 0.1 programs are switched off. It cannot be downgraded in another order. This is strange, and it is very "Xuan Xue ". Tracking code to the underlying layer, and all such releases are available. Why? It may be related to the linux memory management mechanism. Naturally, after the heap memory is allocated to the program in linux, when the program is free, the memory will not be immediately returned to the system, but will be handed over to Ptmalloc, in this way, the program can directly fetch the memory from Ptmalloc without applying to the system, which is more efficient. Ptmalloc does not mean that the memory will not be returned to the system. The mechanism for returning the memory is called "memory shrinkage". When the idle memory on the heap is greater than the shrinkage threshold (kb by default), it will be triggered. Note: The required idle memory must be located at the top of the heap. If the memory on the top of the heap is not released, the memory shrinkage cannot be triggered if the memory on the bottom of the heap is released, this leads to the result of the metaphysics. Therefore, add such a mallopt (M_MMAP_THRESHOLD, 128) in the Code; and M_MMAP_THRESHOLD is the mmap allocation threshold. When the program wants to allocate memory larger than M_MMAP_THRESHOLD, it directly calls mmap () to allocate memory, when it is free, it will directly call munmap () to return the memory to the operating system, instead of being managed by the Ptmalloc cache. So after the connection is closed, the memory will be able to go down. The disadvantage of this is that more memory is needed, and the amount of memory is increased as the M_MMAP_THRESHOLD value decreases. Therefore, you need to select an appropriate number. And the memory is no longer reused, And the allocation efficiency will be relatively low. However, mmap () is the most efficient method for allocating large memory blocks with a long life cycle. Ptmalloc is not good at managing memory with a long life cycle, in particular, the memory is allocated and released occasionally for a long life cycle, which leads to a sudden increase in memory.