mutex를 활용한 타이머 구현

EEEFFEE·2023년 12월 3일
0

kdt system-project note

목록 보기
6/15

23.12.03 최초 작성

  • /ui/input.c : 메시지를 한 글자씩 번갈아가며 출력하는 코드 추가

#define TOY_BUFFSIZE 1024

static pthread_mutex_t global_message_mutex  = PTHREAD_MUTEX_INITIALIZER;

// global_message <~ 모든 문제를 만드는 전역 변수
static char global_message[TOY_BUFFSIZE];//=  "Hello Sir";

...

int (*builtin_func[]) (char **) = {
    &toy_send,
    &toy_shell,
    &toy_exit
};

...

//global_message의 내용을 한 글자 씩 모니터에 출력하는 코드
void *sensor_thread(void* arg)
{
    char saved_message[TOY_BUFFSIZE];
    char *s = arg;

    printf("%s", s);

    int i = 0;
    int mkey = 0;
    printf("%s", s); 

    while (1) {
        i = 0;
        mkey = 0;
        
        // 한 글자씩 출력 후 슬립
        mkey = pthread_mutex_lock(&global_message_mutex);
        if (mkey != 0){
            perror("Sensor mutex lock error");
            exit(0);
        }
        while (global_message[i] != '\0') {
            printf("\t\t%c", global_message[i]);
            fflush(stdout);
            sleep(5);
            i++;
        }
        mkey = pthread_mutex_unlock(&global_message_mutex);
            if (mkey != 0){
                perror("Sensor mutex unlock error");
                exit(0);
            }
        sleep(5);
    }

    return 0;
}

...

//	뮤텍스를 조작하는 함수
int toy_mutex(char **args)
{
    int mkey = 0;
    if (args[1] == NULL) {
        return 1;
    }

    printf("save message: %s\n", args[1]);
    
    mkey = pthread_mutex_lock(&global_message_mutex);
    if(mkey != 0){
        perror("Toy mutex lock error");
        exit(0);
    }
    strcpy(global_message, args[1]);
    mkey = pthread_mutex_lock(&global_message_mutex);
    if(mkey != 0){
        perror("Toy mutex unlock error");
        exit(0);
    }
    return 1;
}

...

int toy_exit(char **args)
{
    return 0;
@@ -290,13 +333,22 @@ void toy_loop(void)
    char *line;
    char **args;
    int status;

    int mkey;
    do {
        mkey = pthread_mutex_lock(&global_message_mutex);
        if (mkey != 0){
                perror("Toy loop mutex lock error");
                exit(0);
        }
        printf("TOY>");
        mkey = pthread_mutex_unlock(&global_message_mutex);
        if (mkey != 0){
                perror("Toy loop mutex unlock error");
                exit(0);
        }
        
        ...
        
}

0개의 댓글

관련 채용 정보