기술(Tech, IT)/임베디드 (Embedded)
[Embedded] Multithreading System - 특정 코어 지정 구현 2
Daniel803
2024. 7. 14. 04:46
Linux (C 구현)와 Windows (C++ 구현)에서 CPU affinity(선호도) 설정 구현 예시를 살펴보자. 이 예시에서는 프로세스(Linux)와 스레드(Windows)를 CPU 0에 바인딩한다. mask를 수정해 다른 또는 여러 CPU에 바인딩할 수 있다. 예를 들어, CPU 0과 CPU 1에 모두 바인딩하려면 Windows에서는 mask를 3(binary 11)으로 설정하고 Linux에서는 CPU_SET(1, &mask)를 사용한다.
- Linux (Using C)
: Linux에서 'sched_setaffinity()' 함수를 사용한 구현 예시다.- cpu_set_t mask
: CPU 세트를 정의하는 자료구조 - CPU_ZERO(&mask)
: CPU 세트를 비어있는 상태로 초기화 - CPU_SET(0, &mask)
: CPU 0을 세트에 추가 - sched_setaffinity(pid, sizeof(mask), &mask)
: 'pid'를 통해 식별한 프로세스의 선호도를 'mask'에 할당된 CPU에 설정
- cpu_set_t mask
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <unistd.h>
int main() {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask); // Bind to CPU 0
pid_t pid = getpid(); // Get the current process ID
if (sched_setaffinity(pid, sizeof(mask), &mask) == -1) {
perror("sched_setaffinity");
return 1;
}
// Your multithreading code here
return 0;
}
- Windows (Using C++)
: Windows에서 'SetThreadAffinityMask' 함수를 사용해 특정 스레드에 CPU affinity를 지정한 구현 예시다.- DWORD_PTR mask = 1
: CPU를 지정하는 mask를 정의(1은 CPU 0, 2는 CPU 1등에 해당) - GetCurrentThread()
: 현제 스레드에 대한 핸들을 획득 - SetThreadAffinity(thread, mask)
: 지정된 스레드에 대한 스레드 선호도를 mask의 CPU로 설정
- DWORD_PTR mask = 1
#include <windows.h>
#include <iostream>
#include <thread>
void threadFunction() {
DWORD_PTR mask = 1; // Bind to CPU 0
HANDLE thread = GetCurrentThread();
SetThreadAffinityMask(thread, mask);
// Your multithreading code here
while (true) {
// Simulate work
Sleep(1000);
}
}
int main() {
std::thread t(threadFunction);
t.join();
return 0;
}
반응형