Big "internal" Expert [Shared Memory and local thread storage]

Source: Internet
Author: User

People in the city want to go out and people outside the city want to come in. This is a sentence in besieged city. It may be more famous than besieged city. I think the premise is that either living in the city or living out of the city can only be one of them. Otherwise, if you want to live in the city, you can live in the city. If you want to live out of the city, you can choose to live in the city on a single day. If you live out of the city on a two-day basis, you have no idea whether to go out or come in.

Ideally, you can live in the city and outside the city, instead of going to the extreme. Although amphibious animals like frogs will never be more advanced than humans, the ability to adapt to more environments has its advantages. The same is true for technology. Shared Memory and local thread storage are instances. They are the product of two extremes: full isolation of memory and full sharing.

When we invented MMU, we thought the world was too peaceful, and the various processes were independent of each other, so the program stability would be greatly improved. But I realized immediately that the process is completely isolated because information sharing is required between processes. So we came up with something called shared memory.

When we invented the thread, we thought it was better that the thread could be executed concurrently, and the overhead of creation and switching was much lower than that of the process. The memory between threads is shared, and inter-thread communication is fast and convenient. But I realized immediately that some information is still not shared, so we should keep every thread a little bit of privacy. So we came up with a local thread storage plug-in.

Shared Memory and local thread storage are two important and uncommon things. They are rarely used at ordinary times, but sometimes they cannot be left behind. This article introduces the concepts, principles, and usage of the two, and puts them in their own toolbox for the occasional needs.

1. Shared Memory
As we all know, process spaces are independent and they do not affect each other. For example, the memory with the 0xabcd1234 address is different in different processes and it does not matter. There are many advantages: each process has a larger address space, and they exclusively occupy 4G (32-bit) address space, making programming easier. The space of each process is independent. A process is dead and does not affect other processes. This improves system stability.

To make the process space independent, it is difficult to implement it by software alone. It usually depends on the help of hardware. This kind of hardware is usually called the memory manage unit (MMU. In this architecture, memory is divided into physical memory and virtual memory. Physical memory is the actual memory, and the size of memory is as large as the size of your machine. In applications, virtual memory is used. When Accessing memory data, MMU converts the virtual memory address to the corresponding physical memory address based on the page table.

MMU maps the virtual memory of each process to different physical memory, thus ensuring that the virtual memory of the process is independent. However, physical memory is often far less than the total virtual memory of each process. What should I do? The general method is to write the memory that is not used for the time being to the disk and load it back into the memory when it is used. A dedicated partition is usually used to store memory data. This is called a swap partition.

These tasks are completed by the kernel and MMU hardware. Memory Management is an important function of the operating system kernel. Many advanced technologies are used to optimize performance. Therefore, memory management is usually complicated. For example, when deciding what data to replace with the disk, we should adopt the least recently used strategy to put the commonly used memory data in the physical memory and write the infrequently used data to the disk, this policy is assumed to be rarely used in the future if it is the least recently used. Cow (copy on write) technology is used to create a process, greatly reducing the replication of memory data. To speed up the conversion from a virtual address to a physical address, the hardware usually uses the TLB technology to store the converted address in the cache and can be used directly next time.

The ing from virtual memory to physical memory is not a byte ing, but is based on a minimum unit called page, the page size depends on the hardware platform, usually 4 K. When the page on which the application accesses the memory is not in the physical memory, MMU generates a page-missing interruption and suspends the current process. The page-missing interruption is responsible for reading the corresponding data from the disk into the memory, then wake up the suspended process.

Shows the ing between virtual memory and physical memory of a process (the gray page is a page that is not in the physical memory ):

 

 

Maybe we seldom use shared memory directly. In fact, unless there are special performance requirements, I prefer to use socket or pipeline as the way of inter-process communication. However, we often use shared memory indirectly. We all know that the advantage of shared libraries (or dynamic libraries) Is that multiple applications can be shared. If each application loads a shared library to the memory, it is a waste of time. Therefore, the operating system places the shared library in the shared memory to share multiple applications. In addition, when the same application runs multiple instances, the same method is used to ensure that there is only one executable code in the memory. Such shared memory is set to read-only to prevent applications from inadvertently damaging them. When the debugger wants to set a breakpoint, the corresponding page is copied to a point, set to writable, and then write the breakpoint command to it. These tasks are completely handled by the operating system and other underlying software, and the application itself does not need to care about them.

How is shared memory implemented? Let's take a look (the yellow page is shared memory ):

 

 

As you can see, it is very easy to implement shared memory, just map the virtual memory of the two processes to the same physical memory. Note that the physical memory is the same, but the virtual address is not necessarily the same. The page5 of process 1 and page2 of process 2 are mapped to page1 of the physical memory.

How can I use shared memory in a program? It is usually very simple. The operating system or function library provides some APIs for us to use. For example:

Linux:
Void * MMAP (void * Start, size_t length, int Prot, int flags, int FD, off_t offset );
Int munmap (void * Start, size_t length );

Win32:
Handle createfilemapping (
Handle hfile, // handle to file
Lpsecurity_attributes lpattributes, // Security
DWORD flprotect, // Protection
DWORD dwmaximumsizehigh, // High-Order DWORD of size
DWORD dwmaximumsizelow, // low-order DWORD of size
Lptstr lpname // Object Name
);
Bool unmapviewoffile (
Lpcvoid lpbaseaddress // starting address
);

2. Local thread storage (TLS)
The memory space of multiple threads in the same process is shared (except for the stack). The memory content modified in one thread takes effect for all threads. This is both an advantage and a disadvantage. It is an advantage, and the thread data exchange becomes very fast. It is a disadvantage. A thread is dead, and other threads are not guaranteed. Multiple Threads access Shared data, which requires expensive synchronization overhead and easily cause synchronization-related bugs ;.

In UNIX, we have always been not very interested in threads. We didn't introduce threads until very late. For example, X sever processes connections from N clients at the same time and responds to millions of requests every second. Developers would rather implement their own scheduling mechanism than use threads. It is hard to imagine that X Server is a single-process, single-thread model. Another example is Apache (1.3x). The implementation in UNIX also uses a multi-process model, which puts public information such as the scoreboard into the shared memory, and is unwilling to adopt a multi-thread model.

As mentioned in "Unix programming art", the emergence of local thread storage makes this situation a turning point. Local thread storage is used, and each thread has a certain amount of private space. This can avoid some unintentional damages, but it still cannot avoid intentional damages.

In my opinion, this is entirely because Unix programs do not like the object-oriented method. The data is not well encapsulated, and global variables are everywhere. In the case of multithreading, problems may naturally occur. If the object-oriented method is used, this situation can be greatly improved without the need for local thread storage.

Of course, there is one more technology and one more choice. It is useful to know the local storage of threads. Although only a few local thread storage methods are used, in that case, there is no local thread storage, and it is really difficult to implement it using other methods.

Local thread storage has different implementations on different platforms, and the portability is not very good. Fortunately, it is not difficult to implement local thread storage. The simplest way is to create a global table and query the corresponding data through the current thread ID, because the IDs of each thread are different, the data found is naturally different.

Most Platforms provide a local thread storage method. We do not need to implement it ourselves:

Linux:
Method 1:
Int pthread_key_create (pthread_key_t * Key, void (* destructor) (void *));
Int pthread_key_delete (pthread_key_t key );
Void * pthread_getspecific (pthread_key_t key );
Int pthread_setspecific (pthread_key_t key, const void * value );
Method 2:
_ Thread int I;
Win32
Method 1:
DWORD tlsalloc (void );
Bool tlsfree (
DWORD dwtlsindex // TLS Index
);
Bool tlssetvalue (
DWORD dwtlsindex, // TLS Index
Lpvoid lptlsvalue // value to store
);
Lpvoid tlsgetvalue (
DWORD dwtlsindex // TLS Index
);
Method 2:
_ Declspec (thread) int tls_ I = 1;

 

Address: http://blogold.chinaunix.net/u2/67414/showart_1778073.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.