스케줄링

아무개·2024년 9월 23일

C/C++

목록 보기
5/6
#include <stdio.h>
#include <windows.h>

#define BTS_TASK_PERIOD (1000) // ms
#define EXO_TASK_PERIOD (2000) // ms
#define HOT_TASK_PERIOD (3000) // ms

static int cnt = 0;
char n;
static int bts_period = BTS_TASK_PERIOD / 1000;
static int exo_period = EXO_TASK_PERIOD / 1000;
static int hot_period = HOT_TASK_PERIOD / 1000;

void bts(void) {
	if (cnt % bts_period == 0) {
		printf(" bts()");
	}
}

void exo(void) {
	if (cnt % exo_period == 0) {
		printf(" exo()");
	}
}

void hot(void) {
	if (cnt % hot_period == 0) {
		printf(" hot()");
	}
}

int main() {
	
	while (1) {

		for (int i = 0; i < 20; i++) {
			if (_kbhit()) {
				n = _getch();
				if (n == '1') printf("key 1 pressed\n");
				else if (n == '2') printf("key 2 pressed\n");
				else if (n == '3') printf("key 3 pressed\n");
				else if (n == '4') printf("key 4 pressed\n");
			}
			Sleep(50);
		}

		cnt++;
		//Sleep(1000);
		printf("\n[%d] ", cnt);

		bts();
		exo();
		hot();
	}
}

windows.h의 Sleep()함수 이용
키입력을 실시간으로 받기 위해 1000ms를 50ms로 나눠서 키입력받는거랑 Sleep()이랑 번갈아 실행

#include <iostream>
#include <thread>
#include <chrono>
#include <conio.h>

#define BTS_TASK_PERIOD (1000) // ms
#define EXO_TASK_PERIOD (2000) // ms
#define HOT_TASK_PERIOD (3000) // ms

static int cnt = 0;
char n;
static int bts_period = BTS_TASK_PERIOD / 1000;
static int exo_period = EXO_TASK_PERIOD / 1000;
static int hot_period = HOT_TASK_PERIOD / 1000;

void bts() {
    if (cnt % bts_period == 0) {
        std::cout << "bts() ";
    }
}

void exo() {
    if (cnt % exo_period == 0) {
        std::cout << "exo() ";
    }
}

void hot() {
    if (cnt % hot_period == 0) {
        std::cout << "hot() ";
    }
}

void ms() {
    cnt++;
    std::cout << "\n[" << cnt << "] ";
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}

void button() {
    while (1) { // 계속 키보드 입력을 감시
        if (_kbhit()) {
            n = _getch();
            if (n == '1') std::cout << "key 1 pressed\n";
            else if (n == '2') std::cout << "key 2 pressed\n";
            else if (n == '3') std::cout << "key 3 pressed\n";
            else if (n == '4') std::cout << "key 4 pressed\n";
        }
    }
}

int main() {

    std::thread th0(&button);
    
    while (1) {
        std::thread th1(&ms);
        th1.join();

        std::thread th2(&bts);
        std::thread th3(&exo);
        std::thread th4(&hot);

        th2.join();
        th3.join();
        th4.join();
    }

    th0.join();
    return 0;
}

cnt 전역변수 이용 ms를 실행하는 스레드는 실행후 바로 종료 그다음 th2 ~4까지 스레드 실행 그리고 종료
th0는 키입력받는 스레드이므로 while(1)을 선언해 계속 돌아가도록 함

profile
생각 정리

0개의 댓글