[C++] Shared Memory

HyoSeok·2024년 9월 30일

writer.cpp

#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <chrono>
#include <thread>

int main() {
    const char* sharedMemoryName = "/shared_memory";
    const size_t sharedMemorySize = 1024;

    // 공유 메모리 생성
    int shm_fd = shm_open(sharedMemoryName, O_CREAT | O_RDWR, 0666);
    ftruncate(shm_fd, sharedMemorySize);

    // 메모리 매핑
    double* shared_data = static_cast<double*>(mmap(0, sharedMemorySize, PROT_WRITE, MAP_SHARED, shm_fd, 0));

    // 실시간 데이터 작성
    for (int i = 0; i < 100000000; i++) {
        for (int j = 0; j < 256; ++j) {
            shared_data[j] = static_cast<double>(rand()) / RAND_MAX;  
        }
        std::cout << "Writer: Updated data " << i << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    munmap(shared_data, sharedMemorySize);
    close(shm_fd);
    shm_unlink(sharedMemoryName);

    return 0;
}

reader.cpp

#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <chrono>
#include <thread>

int main() {
    const char* sharedMemoryName = "/shared_memory";
    const size_t sharedMemorySize = 1024;

    // 공유 메모리 열기
    int shm_fd = shm_open(sharedMemoryName, O_RDONLY, 0666);

    // 메모리 매핑
    double* shared_data = static_cast<double*>(mmap(0, sharedMemorySize, PROT_READ, MAP_SHARED, shm_fd, 0));

    // 실시간 데이터 읽기
    for (int i = 0; i < 100000000; i++) {
        for (int j = 0 ; j < 256 ; j ++)
        {
            std::cout << "Reader: Data " << i << " " << j << " " << shared_data[j]<<  "\n";
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    // 메모리 해제
    munmap(shared_data, sharedMemorySize);
    close(shm_fd);

    return 0;
}
profile
hola!

0개의 댓글