This is a shared memory question in the operating system.

Asked 2 years ago, Updated 2 years ago, 126 views

Hi, everyone. I keep getting confused about the concept of shared memory from the dinosaur book.

I just brought the producer code.

while(true) {
    while (counter == BUFFER_SIZE); // do nothing

    buffer[in] = next_produced;
    in = (in + 1) % BUFFER_SIZE;
    counter++;
}

Is the item in buffer[] in shared memory a variable that the two processes share?

It's confusing because it's not accurate. What exactly goes in the buffer?

If I'm right, I just need to use the buffer's item, but I wonder why the example uses the shared variable called count separately. Please help me

operating-system

2022-09-21 17:18

1 Answers

Programs that run on top of the OS are called processes, and these processes have different memory spaces.

Even if each process reads or writes the same memory address, it is actually reading and writing different physical memory addresses.

This is to virtualize memory addresses in the OS so that conflicts between different processes do not occur. These features are called virtual memory, pages, segments, and so on, and separate the memory addresses that programs use from the physical memory addresses.

As I said before, the memory space between processes is different, so data exchange through memory access is not possible. If you exchange data between processes through memory access, it will be fast and easy to use. Therefore, the OS provides shared memory, one of the IPCs.

that is, shared memory is used for data exchange through memory access between different processes.

Is the item in buffer[] in shared memory a variable that the two processes share?

Yes, shared memory is the memory shared by the two processes, and the address indicated by buffer is shared memory.

Accessing buffer[in] accesses shared memory, writes and reads values, which means that each element (item) is in shared memory.

It's confusing because it's not accurate. What exactly goes in the buffer?

I can't tell what's in buffer just by the code you uploaded. But since it's shared memory, the memory address allocated by the OS must be bound.

In general, malloc() is used to allocate memory as shown below.

int* buffer = (int*) malloc(BUFFER_SIZE  * sizeof(int));

However, for shared memory, memory is allocated using the API of each OS.

// Linux
int id = shmget((key_t)1234, BUFFER_SIZE * sizeof(int), 0666 | IPC_CREAT);
int* buffer = (int*) shmat(id, NULL, 0);

If I'm right, I just need to use the buffer's item, but I wonder why the example uses the shared variable called count separately. Please help me

The code you uploaded is not enough to know in detail, but it seems to be used to avoid exceeding the size of the allocated shared memory.


2022-09-21 17:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.