기본 콘텐츠로 건너뛰기

공유메모리에 40바이트 읽고 쓰는데 얼마나 충돌날까?

가끔씩 공유메모리에 있는 자료를 n개 프로세스/쓰레드가 읽고 쓰기 위해 접근할 때, 정말 충돌이 나긴할까? 물론 이론은 반드시 나긴 나는데, 이론은 이론이고... 임계영역이 I/O wait이 안 일어날 정도로 짧은 구간이더라도 충돌이 날까?

결론은 충돌난다. ㅡ_-) 덴장... 이래서 잠금장치가 여러개 있는 것이지...


아래 소스를 대충 컴파일해서 돌려보고 Ctrl+C를 눌러보면...

#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <signal.h>

enum
{
    SHM_STR_LEN = 32
};

typedef struct str_t
{
    int len;
    char buf[SHM_STR_LEN+1];
} str_t;

volatile size_t g_total_count(0);
volatile size_t g_crash_count(0);

int g_shmfd(-1);
str_t* g_buf(NULL);

//        make random string...
void
makeRandStr(str_t& buf)
{
    memset(&buf, 0x00, sizeof(buf));

    int i, max(rand()%SHM_STR_LEN);
    for ( i = 0; i < max; i++ )
    {
        buf.buf[i] = (rand()%10) + '0';
    }

    buf.len = max;
    buf.buf[SHM_STR_LEN] = 0x00;
}

//        check str_t structure...
bool
chkBuffer(const str_t& buf)
{
    ++ g_total_count;

    int reallen(strlen(buf.buf));

    bool res(reallen == buf.len);
    if ( res )
    {
        //printf("success!\n");
        return true;
    }

    //printf("crash! len=%d real=%d\nbuf=%s\n",
    //    buf.len, reallen, buf.buf);
    ++ g_crash_count;

    return false;
}

//        signal procedure for productor.
void
productor_sigint(int)
{
    shmctl(g_shmfd, IPC_RMID, NULL);
    exit(0);
}

//        productor makes random-string and memcpy to shared-memory.
void
productor(void)
{
    signal(SIGINT, productor_sigint);
    str_t buf;
    while (true)
    {
        makeRandStr(buf);
        memcpy(g_buf, &buf, sizeof(buf));
        //printf("rand: len=%d\n", g_buf->len, g_buf->buf);
    }
}

//        signal procedure for consumer.
void
consumer_sigint(int)
{
    printf("\ntotal: %d\ncrash: %d\nfail-rate: %2.02f%%\n",
        g_total_count, g_crash_count,
        g_crash_count*100.0/g_total_count);
    shmctl(g_shmfd, IPC_RMID, NULL);
    exit(0);
}

//        consumer reads memcpy from shared-memory and check.
void
consumer(void)
{
    signal(SIGINT, consumer_sigint);
    fprintf(stderr, "Test size: %d\n", sizeof(str_t));
    fprintf(stderr, "Press Ctrl+C...");
    str_t buf;
    while (true)
    {
        memcpy(&buf, g_buf, sizeof(buf));
        chkBuffer(buf);
    }
}

//        main function. make shared-memory and fork!
int
main(int argc, char* argv[])
{
    key_t shmkey(ftok("/dev/null", 1));
    if ( -1 == shmkey )
    {
        printf("%d %s\n", __LINE__, strerror(errno));
        return 0;
    }

    g_shmfd = (shmget(shmkey, sizeof(str_t), 0700|IPC_CREAT));
    if ( -1 == g_shmfd )
    {
        printf("%d %s\n", __LINE__, strerror(errno));
        return 0;
    }

    g_buf = ((str_t*)shmat(g_shmfd, NULL, SHM_RND));
    memset(g_buf, 0x00, sizeof(str_t));

    if ( fork() )
    {
        productor();
    }
    else
    {
        consumer();
    }
}


$ g++ -o shmtest -O3 shmtest.cpp
아주 정확한 방법은 아니지만, 대충 충돌하는 것을 알 수 있을 것이다. 여러 시스템에서 돌렸을 때, 몇 퍼센트가 나올지 궁금하다. 누가 돌려주면 좋겠지만, 아쉽게도 아무도 안 돌릴 것 같다. orz OTL

참고로 아래는 CentOS 5.2에서 살포시 돌려본 결과이다.
$ ./shmtest
Test size: 40
Press Ctrl+C...
total: 186202017
crash: 985010
fail-rate: 0.53%



덧글: 혹시나 오해할까봐... MT/MP 환경에서 임계영역이 있다면 락을 걸어주는 것이 상식. 이건 그냥 가끔씩 이론은 이론이고 실제는 얼마나 충돌할까라는 맛뵈기 실험.

댓글

이 블로그의 인기 게시물

버즈 라이브 배터리 교체

나는 버즈 라이브(SM-R180)가 좋은데, 평가가 별루였는지, 해당 스타일로 버즈를 더 이상 만들지 않고 있다. 아무튼, 오래 쓴 버즈 라이브 배터리가 슬슬 맛이 가기 시작해서, 블로그 를 참조하면서 분해 및 교체를 하였다. (진짜 쉬움) 요로코롬 위아래를 살짝 눌러주면 뚜껑이 벌어진다. 안쪽 플라스틱은 오른쪽은 분홍색, 왼쪽은 회색이다. 리본 케이블 살짝 들어내고, 기판을 떼어내면, 작은 나사가 있다. 나사를 풀고, 플라스틱을 걷어내면, 검은 양면 테이프로 고정된 CR1254 배터리가 보인다. 잘 쑤셔서(?) 꺼낸다. 새로운 CR1254 배터리를 넣는다. 음극이 아래로 가도록 하고, 분해의 역순으로 조립하면 된다. 조립할 때, 아까 풀었던 나사는 잊지 말고 꼭 조여준다. (까먹고 조립해서 다시 뜯고 조립함) 충전도 잘 되고, 소리도 잘 나는거 보면, 조립도 잘 된 것 같다. 이렇게 버즈 라이브의 수명을 강제로 늘렸다. 나중에 본체 배터리도 갈아야겠다.

ESP8266 + TM1637 WIFI 인터넷 시계 만들기

ESP8266 과 TM1637 으로 인터넷 시계 만들기 원래는 다이소에서 판매하는 5000원짜리 시계 뜯어서 만드려고 했는데, 시계를 뜯어보니, 자체 MCU를 통해 제어를 하고 있어 TM1637 로 구현하고 나중에 케이스를 만드는게 나을 것 같아서 아래와 같이 구현(chatGPT)했다. 30분마다 NTP 가져오기 WIFI가 끊기더라도 RTC 유지 WIFI가 끊기면 1분에 한 번씩 재접속 시도 버튼을 3초 누르면, AP 설정 모드 (88:88 표시) #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include <TM1637Display.h> #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #define CLK D5 // TM1637 CLK #define DIO D6 // TM1637 DIO #define CONFIG_BUTTON_PIN D7 // 설정 진입 버튼 TM1637Display display(CLK, DIO); // 시간 관련 변수 time_t currentEpochTime = 0; unsigned long lastNtpMillis = 0; unsigned long checkTermMillis = 1800000UL; // 30분마다 NTP 다시 받아옴 // Wi-Fi 재접속 관련 unsigned long lastWiFiReconnectAttempt = 0; const unsigned long wifiReconnectInterval = 60000; // 1분 // 버튼 관련 unsigned long buttonPressedTime = 0; bool buttonWasHeld = false; const unsigned long CONFIG_HOLD_TIME = 3000; // 3초 bool isInConfigMode = false; const char* ntpServer = ...

Windows 에서 절전을 깨우는 장치 찾기

참조:  https://www.reddit.com/r/computer/comments/wquswv/windows_11_pc_wakes_up_every_time_i_move_usb/ powercfg /devicequery wake_armed powercfg /deviceenablewake "[DEVICE]" # $PROFILE function Get-WakeArmedDevices { $devices = powercfg -devicequery wake_armed if ($devices) { $devices | ForEach-Object { $_.Trim() } } else { Write-Host "No devices are currently armed for wake events." } } function Set-EnableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -deviceenablewake $deviceName } function Set-DisableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -devicedisablewake $deviceName }