Program Club

단일 프로세서 시스템에서 멀티 스레딩을 구현할 수 있습니까?

proclub 2020. 12. 11. 18:58
반응형

단일 프로세서 시스템에서 멀티 스레딩을 구현할 수 있습니까?


멀티 스레딩은 각 스레드에 할당 할 프로세서가 두 개 이상이고 각 스레드가 동시에 실행될 수있는 다중 프로세서 시스템에서만 구현 될 수 있다는 개념을 항상 따랐습니다. 이 경우 각 스레드에는 전용 리소스가 모두 있으므로 예약이 없습니다. 그러나 나는 단일 프로세서 시스템에서도 멀티 스레딩을 할 수있는 곳에서 그것을 읽었습니다. 맞습니까? 그렇다면 단일 프로세서와 다중 프로세서 시스템의 차이점은 무엇입니까?


물론 단일 프로세서 시스템에서 수행 할 수 있으며 실제로 그렇게하는 것이 훨씬 쉽습니다. 타이머 인터럽트 또는 기타 유사한 메커니즘을 통해 커널이 여러 프로세스를 실행하는 것과 동일한 방식으로 작동합니다. 동일한 프로세스의 스레드가 동일한 가상 메모리 공간을 공유하므로 작업 전환이 훨씬 더 효율적입니다.

다중 프로세서 시스템에서 다중 스레딩은 실제로 훨씬 더 어렵습니다. 다중 CPU / 코어에서 메모리에 동시에 액세스하는 문제와 그로 인해 발생하는 모든 불쾌한 메모리 동기화 문제가 있기 때문입니다.


단일 프로세서 시스템에서도 멀티 스레딩을 할 수있는 곳에서 읽었습니다. 맞습니까? 그렇다면 단일 프로세서와 다중 프로세서 시스템의 차이점은 무엇입니까?

예, 단일 프로세서 시스템에서 멀티 스레딩을 수행 할 수 있습니다.

다중 프로세서 시스템에서는 여러 스레드가 서로 다른 코어 에서 동시에 실행 됩니다. 예 : 두 개의 스레드와 두 개의 코어가있는 경우 각 스레드는 개별 코어에서 실행됩니다.

단일 프로세서 시스템에서는 스레드 우선 순위 및 OS 정책에 따라 여러 스레드가 차례로 실행되거나 하나의 스레드가 완료되거나 OS에 의해 선점 될 때까지 대기하지만 실행중인 스레드는 동시에 실행되는 것처럼 보입니다. , 사용자 공간 애플리케이션의 필수 애플리케이션 응답 시간에 상대적입니다.

시간 비교 (예) :

두 개의 스레드가 실행하는 데 각각 10us가 걸리면 2 프로세서 시스템에서 순 소요 시간은 10us입니다.

두 개의 스레드를 실행하는 데 각각 10us가 소요되는 경우 1 프로세서 시스템에서 순 소요 시간은 20us입니다.


쿼드 코어 시스템에는 4 개 이상의 활성 스레드가있을 수 있습니다. 거기 이다 당신이 프로세스가 프로세서가보다 더 많은 스레드를 만들려고하지 않습니다 보장 할 수없는 한 일정은.

예, 단일 코어 컴퓨터에 여러 스레드가있을 수 있습니다.

단일 프로세서와 다중 프로세서 시스템의 차이점은 다중 프로세서 시스템이 실제로 한 번에 둘 이상의 작업을 수행 할 수 있다는 것입니다. 한 번에 N 개의 작업을 수행 할 수 있습니다. 여기서 N은 프로세서 코어 수입니다. 단일 프로세서 코어는 한 번에 한 가지 작업 만 수행 할 수 있습니다. WhozCraig가 자신의 의견에서 말했듯이 실제 동시성과인지 된 동시성의 차이입니다.


다음은 매우 간단한 예입니다. 실제로 제가 만들고있는 프로그램의 프로토 타입입니다. 단일 스레드에서 협력적인 멀티 태스킹을 구현 한 것입니다.

mainquit플래그를 false로 설정하고 함수 포인터 (작업)의 배열을 채운 다음 loop.

loop용도가 setjmp아닌 로컬 점프 (점프하는 리턴 포인트를 설정하는 아웃 실행 이전에 위치 함수 뒷면) 다음 첫 번째 태스크 (함수)를 호출하기 위해 진행한다.

각 작업은 yield(). 즉, 실제로 어떤 작업도 작동하지 않습니다 return. 그들은 return;명령문을 포함하지 않을뿐만 아니라 ( void함수, 즉 프로 시저 이기 때문에 괜찮습니다 ), 호출로 다시 점프 return하기 때문에 거기에 있어도 도달하지 않을 것입니다. 이번에는 명령문에 1을 산출합니다 . 에서 . 문에 의해 제어되는 문은 루프에 다시 들어가기 전에 다른 작업을 선택합니다 .yieldsetjmpifloopifwhile

따라서 각 태스크 함수는 여러 번 실행되어 실행할 새 태스크를 선택하는 디스패처 ( if(setjmp...문)에 양보 합니다.

#include <stdio.h> 
#include <setjmp.h> 

jmp_buf dispatch; 
int ntasks; 
void (*task[10])(void); 
int quit; 

void yield(void) { 
    longjmp(dispatch, 1); 
} 

void loop() { 
    static int i = 0; 
    if(setjmp(dispatch)) 
        i = (i+1) % ntasks; 
    while(!quit) 
        task[i](); 
} 

int acc = 0; 

void a(void) { 
    if (acc > 10) quit = 1; 
    printf("A\n"); 
    yield(); 
} 
void b(void) { 
    acc *= 2; 
    printf("B\n"); 
    yield(); 
} 
void c(void) { 
    acc += 1; 
    printf("C\n"); 
    yield(); 
} 

int main() { 
    quit = 0; 
    ntasks = 3; 
    task[0] = a; 
    task[1] = b; 
    task[2] = c; 
    loop(); 
    return 0; 
} 

The difference between this example and a single-processor multitasking computer system is the real processor supports interrupting a task in the middle of execution and resuming it later from the same spot. This isn't really possible in a C simulation with tasks as single functions. However, the tasks could be composed of a sequence of C functions which each yield to the dispatcher (an array of function pointers, maybe, or a linked-list).


Yes, you totally can. Ages ago (Win 95?) we went from Cooperative Multitasking to Multithreading, because someone always screwed up the cooperative part. Every programm on your computer has at least one thread. Possibly more. And the CPU keep just switching between those all those threads like mad a few million times per second. If none of them has anything to do, it might even go idle for some time.

Multicore systems only mean that two or more of those threads might run in paralell.

However, it brings you a lot less to do so. All you can do with Multithreading on a Single Core machine is simulate Multitasking.

Mulitasking is enough to prevent the GUI thread from locking up because of a longrunning operation. However it is generally complicated to implement, unless you have some help from the Compiler or Langauge (like C# async...await). As a result, many GUI programmer just used Multithreading and Invoking to fake multitasking. If that code runs on single or multiple core does not mater for this.

Most importantly, Multitasking is NOT suited for CPU bound operations. But 95% of all Async problems are not CPU bound. They are Network or Disk Bound. On a singlecore computer, Multithreading also does not help with CPU bound stuff. If you got two threads that both need 100% CPU time (same programm or different one) but only one core to run them on, the CPU will just have to switch between running both at 49% and use the remaining 2% for all those other threads that only do a little bit.

Finally only very few problems can actually be Multithreaded. Just try to multithread the Fibonacci Sequence (one thread for each pair) without making it slower, more memory demanding and more complex.

tl;dr; You need Multithreading and a Multicore computer for CPU bound problems. Most async problems are not CPU bound. Multitasking is way enough. And you can totally multitask using threads, even on a single core machine.

참고URL : https://stackoverflow.com/questions/16116952/can-multithreading-be-implemented-on-a-single-processor-system

반응형