동시성과 병렬성의 차이점은 무엇입니까?
동시성과 병렬성의 차이점은 무엇입니까?
예가 감사합니다.
동시성 은 둘 이상의 작업이 겹치는 기간에 시작, 실행 및 완료 될 수있는 경우입니다. 반드시 둘 다 같은 순간에 실행될 것이라는 의미는 아닙니다. 예를 들어, 단일 코어 시스템 에서 멀티 태스킹이 가능 합니다.
병렬 처리 는 작업이 말 그대로 동시에 실행되는 경우입니다 (예 : 멀티 코어 프로세서에서).
동시성 : 두 개 이상의 스레드가 진행 중일 때 존재하는 조건입니다. 가상 병렬 처리의 한 형태로 시간 분할을 포함 할 수있는보다 일반적인 형태의 병렬 처리입니다.
병렬 처리 : 두 개 이상의 스레드가 동시에 실행될 때 발생하는 조건입니다.
혼란이 존재하는 이유
이 두 단어의 사전 적 의미가 거의 동일하기 때문에 혼란이 존재합니다.
- 동시 접속 : 기존, 진행중, 동시에 완료 (dictionary.com)
- 병렬 : 매우 유사하고 종종 동시에 발생합니다 (메리 암 웹스터).
그러나 컴퓨터 과학과 프로그래밍에서 사용되는 방식은 상당히 다릅니다. 내 해석은 다음과 같습니다.
- 동시성 : 인터럽트 가능성
- 병렬성 : 독립성
그렇다면 위의 정의는 무엇을 의미합니까?
나는 현실 세계의 비유로 명확히 할 것이다. 하루에 두 가지 중요한 작업을 완료해야한다고 가정 해 보겠습니다.
- 여권 받기
- 프레젠테이션 완료
이제 문제는 task-1이 여권을 받기 위해 줄을 서서 4 시간을 기다려야하는 극도로 관료적 인 관공서에 가야한다는 것입니다. 한편 작업 -2는 사무실에서 필요하며 중요한 작업입니다. 둘 다 특정 날짜에 완료되어야합니다.
사례 1 : 순차적 실행
일반적으로 여권 사무소에 2 시간 동안 운전하고, 4 시간 동안 줄을 서고, 작업을 완료하고, 2 시간 뒤로 운전하고, 집에 돌아가고, 5 시간 더 깨어 있고, 프레젠테이션을 완료합니다.
사례 2 : 동시 실행
하지만 당신은 똑똑합니다. 당신은 미리 계획합니다. 노트북을 가지고 다니며 줄을 서서 기다리는 동안 프레젠테이션 작업을 시작합니다. 이렇게하면 집에 돌아 오면 5 시간이 아닌 1 시간 만 더 일하면됩니다.
이 경우 두 작업은 모두 사용자가 수행합니다. 줄을 서서 기다리는 동안 여권 작업을 중단하고 프레젠테이션 작업을했습니다. 번호가 호출되었을 때 프레젠테이션 작업을 중단하고 여권 작업으로 전환했습니다. 두 작업의 중단 가능성으로 인해 시간을 절약 할 수있었습니다.
동시성, IMO는 ACID 에서 "격리"속성으로 이해 될 수 있습니다 . 하위 트랜잭션이 각각 인터리브 방식으로 수행 될 수 있고 최종 결과는 두 작업이 순차적으로 수행 된 것과 동일한 경우 두 개의 데이터베이스 트랜잭션이 격리 된 것으로 간주됩니다. 여권과 제시 작업 모두에서 당신은 유일한 사형 집행 자라는 것을 기억하십시오 .
사례 3 : 병렬 실행
자, 당신은 똑똑한 친구이기 때문에 분명히 더 높은 사람이고 비서가 있습니다. 따라서 여권 작업을 시작하기 위해 떠나기 전에 그에게 전화를 걸어 프레젠테이션 초안을 준비하라고 말합니다. 하루 종일을 보내고 여권 작업을 마치고 돌아와서 메일을보고 프레젠테이션 초안을 찾습니다. 그는 꽤 견고한 작업을 수행했으며 2 시간 만 더 편집하여 완료합니다.
이제 당신의 어시스턴트는 당신만큼 똑똑하기 때문에 끊임없이 설명을 요구할 필요없이 독립적 으로 작업 할 수있었습니다 . 따라서 작업의 독립성으로 인해 두 명의 다른 실행자가 동시에 수행했습니다 .
아직도 나와 함꼐? 좋구나...
사례 4 : 동시 적이지만 병렬이 아님
줄에서 기다려야하는 여권 작업을 기억하십니까? 이 때문에 귀하의 여권, 비서는 당신을 위해 줄을 기다릴 수 없습니다. 따라서 여권 작업은 중단 할 수 있지만 (줄에서 대기하는 동안 중지하고 나중에 번호가 호출되면 다시 시작할 수 있음) 독립성 은 없습니다 (비서가 대신 기다릴 수 없음).
사례 5 : 병렬이지만 동시 적이 지 않음
관공서에 건물에 들어가기위한 보안 검사가 있다고 가정합니다. 여기에서 모든 전자 장치를 제거하고 경찰관에게 제출해야하며 작업을 완료 한 후에 만 장치를 반환합니다.
이 경우 여권 작업은 독립적 이거나 중단 할 수 없습니다 . 줄을 서고 있어도 필요한 장비가 없기 때문에 다른 작업을 할 수 없습니다.
마찬가지로 프레젠테이션이 본질적으로 매우 수학적이므로 최소 5 시간 동안 100 % 집중해야합니다. 노트북을 가지고 있어도 여권 작업을 기다리는 동안에는 할 수 없습니다.
이 경우 프레젠테이션 작업은 독립적으로 수행 할 수 있지만 (사용자 또는 보조자가 5 시간 동안 집중적으로 노력할 수 있음) 중단 할 수는 없습니다 .
사례 6 : 동시 및 병렬 실행
이제 프레젠테이션에 조수를 할당하는 것 외에도 여권 작업에 노트북을 가지고 다니고 있다고 가정합니다. 줄을서는 동안 어시스턴트가 공유 데크에 처음 10 개의 슬라이드를 만든 것을 볼 수 있습니다. 그의 작업에 대한 의견을 몇 가지 수정하여 보냅니다. 나중에 집에 도착하면 초안을 완성하는 데 2 시간이 걸리지 않고 15 분이면 충분합니다.
이것은 프레젠테이션 작업이 독립성 (둘 중 한 사람이 할 수 있음)과 중단 성 (중지했다가 나중에 다시 시작할 수 있음 ) 이 있기 때문에 가능 했습니다. 따라서 두 작업 을 동시에 실행 하고 프레젠테이션 작업을 병렬로 실행했습니다.
과도하게 관료주의적일뿐만 아니라 관료가 부패했다고 가정 해 봅시다. 따라서 신분증을 보여주고, 입력하고, 전화 번호가 호출 될 때까지 줄을 서기 시작하고, 경비원과 다른 사람에게 뇌물을주고, 전화를 걸기 전에 다시 돌아와 대기를 재개 할 수 있습니다. 당신 자신.
이 경우 여권 및 프레젠테이션 작업을 동시에 수행 할 수 있습니다. 몰래 빠져 나갈 수 있으며 위치는 비서가 보유합니다. 두 사람 모두 프레젠테이션 작업 등을 할 수 있습니다.
컴퓨터 과학으로 돌아 가기
컴퓨팅 세계에서 이러한 각 경우에 대한 일반적인 예제 시나리오는 다음과 같습니다.
- 사례 1 : 인터럽트 처리.
- 사례 2 : 프로세서가 하나만 있지만 실행중인 모든 작업에 I / O로 인해 대기 시간이있는 경우.
- 사례 3 : map-reduce 또는 Hadoop 클러스터에 대해 이야기 할 때 자주 나타납니다.
- 사례 4 : 사례 4는 드물다고 생각합니다. 작업이 동시에 이루어 지지만 병렬이 아닌 경우는 드뭅니다. 그러나 수 일. 예를 들어, 작업이 프로세서 -1을 통해서만 액세스 할 수있는 특수 계산 칩에 대한 액세스를 필요로한다고 가정합니다. 따라서, 프로세서 -2가 비어 있고 프로세서 -1이 다른 작업을 수행하고 있어도 특수 계산 작업은 프로세서 -2에서 진행할 수 없습니다.
- 사례 5 : 또한 드물지만 사례 4만큼 드물지는 않습니다. 비 동시 코드는 뮤텍스로 보호되는 중요 영역이 될 수 있습니다. 일단 시작되면 완료 될 때 까지 실행 되어야합니다 . 그러나 두 개의 다른 중요 영역은 두 개의 다른 프로세서에서 동시에 진행될 수 있습니다.
- 사례 6 : IMO, 병렬 또는 동시 프로그래밍에 대한 대부분의 논의는 기본적으로 사례 6에 대한 것입니다. 이것은 병렬 실행과 동시 실행의 혼합 및 일치입니다.
동시성 및 이동
Rob Pike가 동시성이 더 낫다고 말하는 이유를 알면 그 이유를 이해해야합니다. 파일 읽기, 네트워크 다운로드와 같은 일부 외부 작업을 기다리는 여러 대기 기간이있는 정말 긴 작업이 있습니다. 그의 강연에서 그가 말하는 모든 것은 "기다리는 동안 유용한 일을 할 수 있도록이 긴 연속적인 작업을 나누기 만하면됩니다." 그래서 그는 다양한 고퍼들과 함께 다양한 조직에 대해 이야기합니다.
이제 Go의 강점은 go
키워드와 채널을 사용하여 쉽게 깨뜨리는 데 있습니다. 또한 이러한 고 루틴을 예약하기 위해 런타임에 뛰어난 기본 지원이 있습니다.
그러나 본질적으로 동시성이 병렬 처리보다 더 낫습니까?
사과가 오렌지보다 낫습니까?
나는 Rob Pike의 이야기를 좋아합니다 : 동시성은 병렬성이 아닙니다 (더 낫습니다!) (슬라이드) (토론)
Rob은 일반적으로 Go에 대해 이야기하고 일반적으로 시각적이고 직관적 인 설명으로 동시성 대 병렬성 문제를 해결합니다! 다음은 간단한 요약입니다.
과제 : 쓸모없는 언어 매뉴얼 더미를 태우 자! 한번에 한!
동시성 : 작업의 동시 분해가 많이 있습니다! 한 가지 예 :
병렬 처리 : 동시에 작동하는 고퍼가 2 개 이상인 경우 이전 구성이 병렬로 발생합니다.
다른 사람들이 말한 내용을 추가하려면 :
동시성은 요술쟁이가 많은 공을 저글링하는 것과 같습니다. 어떻게 보이는지에 관계없이, 저글러는 한 손에 한 번에 하나의 공만 잡거나 던집니다. Parallelism은 여러 juggler가 동시에 공을 저글링하는 것입니다.
두 개의 스레드가있는 프로그램이 있다고 가정하십시오. 이 프로그램은 두 가지 방법으로 실행할 수 있습니다.
Concurrency Concurrency + parallelism
(Single-Core CPU) (Multi-Core CPU)
___ ___ ___
|th1| |th1|th2|
| | | |___|
|___|___ | |___
|th2| |___|th2|
___|___| ___|___|
|th1| |th1|
|___|___ | |___
|th2| | |th2|
두 경우 모두 하나 이상의 스레드가 실행되고 있다는 단순한 사실로 인해 동시성이 있습니다.
단일 CPU 코어가있는 컴퓨터에서이 프로그램을 실행하면 OS가 두 스레드 사이를 전환하여 한 번에 하나의 스레드를 실행할 수 있습니다.
이 프로그램을 멀티 코어 CPU가있는 컴퓨터에서 실행하면 두 스레드를 동시에 병렬 로 실행할 수 있습니다 .
동시성 : 단일 프로세서로 둘 이상의 문제가 해결되는 경우.
병렬 처리 : 하나의 문제가 여러 프로세서로 해결되는 경우.
흥미롭고 이해하기 쉬운 예를 들어 설명하겠습니다. :)
한 조직에서 10 명의 플레이어 ( 동일한 체스 플레이 기술 )가 프로 챔피언 체스 플레이어 에게 도전하는 체스 토너먼트를 조직 한다고 가정 합니다 . 그리고 체스는 1 : 1 게임이기 때문에 주최측은 최대한 빨리 전체 이벤트를 완료 할 수 있도록 10 개의 게임을 시간 효율적으로 진행해야합니다.
다음 시나리오에서이 10 가지 게임을 수행하는 여러 방법을 쉽게 설명 할 수 있기를 바랍니다.
1) SERIAL- 전문가가 각 사람과 하나씩 플레이한다고 가정 해 봅시다. 즉, 한 사람과 게임을 시작하고 끝낸 다음 다음 사람과 다음 게임을 시작하는 식입니다. 즉, 그들은 게임을 순차적으로 진행하기로 결정했습니다. 따라서 한 게임을 완료하는 데 10 분이 걸리면 10 게임이 100 분이 걸리고, 한 게임에서 다른 게임으로 전환하는 데 6 초가 걸린다고 가정하고 10 게임의 경우 54 초 (약 1 분)가 걸린다고 가정합니다.
전체 이벤트가 약 101 분 안에 완료됩니다 ( 최악의 접근 방식 )
2) CONCURRENT- 프로 선수가 자신의 차례를 플레이하고 다음 선수로 이동하여 10 명의 선수 모두가 동시에 플레이하지만 프로 선수가 한 번에 두 사람과 함께 있지 않고 자신의 차례를 플레이하고 다음 선수로 이동한다고 가정 해 보겠습니다 . 이제 프로 선수가 자신의 턴을 플레이하는 데 6 초가 걸리고 프로 선수 2 명의 전환 시간이 6 초이므로 첫 번째 선수로 돌아가는 총 전환 시간은 1 분 (10x6 초)이라고 가정합니다. 따라서 이벤트가 시작된 1 인칭 시점으로 돌아올 때까지 2 분 (10xtime_per_turn_by_champion + 10xtransition_time = 2mins)이 지났습니다.
모든 플레이어가 자신의 턴을 완료하는 데 45 초가 걸린다고 가정하면 SERIAL 이벤트에서 게임당 10 분을 기준으로 할 수 있습니다. 게임이 끝나기 전에 라운드 수는 600 / (45 + 6) = 11 라운드 (대략) 여야합니다.
따라서 전체 이벤트는 대략 11xtime_per_turn_by_player _ & _ champion + 11xtransition_time_across_10_players = 11x51 + 11x60sec = 561 + 660 = 1221sec = 20.35 분 (대략) 후에 완료됩니다.
101 분에서 20.35 분까지 개선 사항 확인 ( 더 나은 접근 방식 )
3) PARALLEL- 주최자가 약간의 추가 자금을 받아 두 명의 프로 챔피언 플레이어 (둘 다 똑같은 능력) 를 초대 하고 같은 10 명의 플레이어 (도전자)를 각각 5 명씩 두 그룹으로 나누어 두 명의 챔피언, 즉 1 명에게 할당했다고 가정 해 보겠습니다. 각각 그룹화하십시오. 이제 이벤트는이 두 세트에서 병렬로 진행됩니다. 즉, 최소 두 명의 선수 (각 그룹에 한 명)가 각 그룹의 두 프로 선수와 대결합니다.
그러나 그룹 내에서 프로 선수는 한 번에 한 명의 선수를 (즉, 순차적으로) 데려가므로 계산없이 전체 이벤트가 완료하는 데 약 101 / 2 = 50.5 분 내에 완료 될 것이라고 쉽게 추론 할 수 있습니다.
101 분에서 50.5 분까지 개선 사항 확인 ( 좋은 접근 방식 )
4) CONCURRENT + PARALLEL- 위의 시나리오에서 두 챔피언 플레이어가 각 그룹의 5 명의 플레이어와 동시에 플레이 (2 번째 포인트 읽기)하므로 이제 그룹 간 게임이 병렬로 실행되지만 그룹 내에서는 동시에 실행됩니다.
따라서 한 그룹의 게임은 대략 11xtime_per_turn_by_player _ & _ champion + 11xtransition_time_across_5_players = 11x51 + 11x30 = 600 + 330 = 930sec = 15.5 분 (대략) 후에 완료됩니다.
따라서 전체 이벤트 (이러한 병렬 실행 그룹 2 개 포함)는 대략 15.5 분 안에 완료됩니다.
101 분에서 15.5 분까지 개선 사항 확인 ( 최상의 접근 방식 )
참고 : 위의 시나리오에서 10 명의 플레이어를 10 개의 유사한 직업으로 교체하고 2 명의 프로 플레이어를 2 개의 CPU 코어로 교체하면 다음 순서가 그대로 유지됩니다.
SERIAL> PARALLEL> CONCURRENT> CONCURRENT + PARALLEL
(참고 :이 순서는 작업의 상호 의존성, 통신에 필요한 흑백 작업 및 전환 오버 헤드 흑백 작업에 따라 크게 달라 지므로 다른 시나리오에서는이 순서가 변경 될 수 있습니다.)
간단한 예 :
동시 개최 : "하나의 ATM 기계에 액세스하는 두 개의 대기열"
병렬은 "2 개의 대기열과 2 개의 ATM 기계"입니다.
동시성 : 리소스를 공유 할 수있는 여러 실행 흐름
예 : I / O 포트를 놓고 경쟁하는 두 개의 스레드.
병렬성 : 문제를 여러 개의 유사한 청크로 분할합니다.
예 : 파일의 절반마다 두 개의 프로세스를 실행하여 큰 파일을 구문 분석합니다.
그들은 다른 문제를 해결합니다. 동시성은 부족한 CPU 리소스와 많은 작업 문제를 해결합니다. 따라서 부족한 리소스에 대한 시간을 공유하기 위해 코드를 통해 스레드 또는 독립적 인 실행 경로를 만듭니다. 최근까지 CPU 가용성 때문에 동시성이 논의를 지배했습니다.
병렬 처리는 충분한 작업과 적절한 작업 (올바르게 분리 될 수있는 작업)을 찾고이를 충분한 CPU 리소스에 분산시키는 문제를 해결합니다. 물론 병렬 처리는 항상 주변에 있었지만 멀티 코어 프로세서가 너무 저렴하기 때문에 선두에 서고 있습니다.
동시 프로그래밍 실행에는 비 병렬 동시 프로그래밍과 병렬 동시 프로그래밍 (병렬 처리라고도 함)의 두 가지 유형이 있습니다.
주요 차이점은 인간의 눈에는 병렬이 아닌 동시성의 스레드가 동시에 실행되는 것처럼 보이지만 실제로는 그렇지 않다는 것입니다. 병렬이 아닌 동시성에서 스레드는 시간 분할을 통해 프로세서를 빠르게 전환하고 번갈아 사용합니다. 병렬 처리에서는 여러 프로세서를 사용할 수 있으므로 여러 스레드가 다른 프로세서에서 동시에 실행될 수 있습니다.
참조 : 프로그래밍 언어의 동시성 소개
비디오 튜토리얼을 보면서 새로운 프로그래밍 언어를 배우는 것을 상상해보십시오. 비디오를 일시 중지하고 코드에서 말한 내용을 적용한 다음 계속 시청해야합니다. 그것은 동시성입니다.
이제 당신은 전문 프로그래머입니다. 코딩하는 동안 차분한 음악을 듣는 것을 즐깁니다. 이것이 바로 병렬성입니다.
즐겨.
병렬 처리는 multiple cores per CPU
또는 에서 프로세스를 동시에 실행하는 것입니다 multiple CPUs (on a single motherboard)
.
동시성 은 CPU의 시간 (시간 분할)을 나누는 스케줄링 알고리즘 을 사용하여 병렬 처리 가 달성되는 경우 입니다. 프로세스가 인터리브 됩니다.single core CPU
단위 :
- 단일 CPU에 1 개 이상의 코어 (대부분의 모든 최신 프로세서)
- 마더 보드에 1 개 이상의 CPU (구식 서버를 생각해보십시오)
- 하나의 응용 프로그램은 하나의 프로그램입니다 (Chrome 브라우저를 생각해보십시오).
- 하나의 프로그램에 하나 이상의 프로세스가있을 수 있습니다 (각 Chrome 브라우저 탭이 하나의 프로세스라고 생각).
- 하나의 프로세스는 하나의 프로그램에서 하나 이상의 스레드를 가질 수 있습니다 (하나의 스레드에서 Youtube 비디오를 재생하는 크롬 탭, 댓글 섹션에 다른 스레드 생성, 사용자 로그인 정보에 대해 다른 스레드).
- 따라서 하나의 프로그램은 하나 이상의 실행 스레드를 가질 수 있습니다.
- 1 개의 프로세스는
thread(s)+allocated memory resources by OS
(힙, 레지스터, 스택, 클래스 메모리)
서버가 대기열에서 첫 번째 작업 만 제공 할 수있는 서비스 대기열로 생각하십시오.
서버 1 개, 작업 대기열 1 개 (작업 5 개 포함)-> 동시성 없음, 병렬 처리 없음 (작업이 하나만 완료 될 때까지 서비스되고 대기열의 다음 작업은 서비스 된 작업이 완료 될 때까지 기다려야하며 다른 서버가 없습니다. 서비스)
1 개의 서버, 2 개 이상의 서로 다른 대기열 (대기열 당 5 개의 작업 포함)-> 동시성 (서버가 대기열의 모든 첫 번째 작업과 동등하거나 가중치가 부여 된 시간을 공유하기 때문에), 어느 순간에도 병렬 처리가 없습니다. 서비스를 받고 있습니다.
2 개 이상의 서버, 하나의 대기열-> 병렬 처리 (동일한 순간에 2 개의 작업 수행) 그러나 동시성은 없습니다 (서버가 시간을 공유하지 않고 세 번째 작업은 서버 중 하나가 완료 될 때까지 기다려야 함).
2 개 이상의 서버, 2 개 이상의 서로 다른 대기열-> 동시성 및 병렬 처리
즉, 동시성은 작업을 완료하는 데 시간을 공유하고 작업을 완료하는 데 같은 시간이 걸릴 수 있지만 적어도 일찍 시작됩니다. 중요한 것은 작업을 더 작은 작업으로 분할하여 인터리빙을 허용한다는 것입니다.
병렬 처리는 병렬로 실행되는 더 많은 CPU, 서버, 사람 등으로 달성됩니다.
리소스가 공유되면 순수한 병렬 처리를 달성 할 수 없지만 동시성이 가장 실용적으로 사용되어 해당 리소스가 필요하지 않은 다른 작업을 수행 할 수 있습니다.
동시성 => 공유 리소스와 겹치는 기간에 여러 작업을 수행하는 경우 (잠재적으로 리소스 활용도 극대화).
병렬 => 단일 작업이 동시에 수행 할 수있는 여러 개의 단순 독립 하위 작업으로 분할 될 때.
여기에서 인기있는 답변 중 일부와 약간 상충되는 답변을 제공하겠습니다. 제 생각에 동시성은 병렬성을 포함하는 일반적인 용어입니다. 동시성 은 별개의 작업 또는 작업 단위가 시간상 겹치는 모든 상황에 적용됩니다. 병렬 처리 는 개별 작업 단위가 동일한 물리적 시간에 평가 / 실행되는 상황에보다 구체적으로 적용됩니다. 병렬 처리의 이유는 여러 물리적 컴퓨팅 리소스를 활용할 수있는 소프트웨어의 속도를 높이는 것입니다. 동시성에 맞는 다른 주요 개념은 상호 작용입니다. 상호 작용작업의 겹침이 외부 세계에서 관찰 될 때 적용됩니다. 상호 작용의 이유는 사용자, 네트워크 피어, 하드웨어 주변 장치 등과 같은 실제 엔티티에 반응하는 소프트웨어를 만드는 것입니다.
병렬성과 상호 작용은 거의 완전히 독립적 인 동시성 차원입니다. 특정 프로젝트의 경우 개발자는 둘 중 하나 또는 둘 다에 관심이 없습니다. 그것들은 합쳐지는 경향이 있습니다. 특히 쓰레드라는 혐오감이 두 가지를 모두 할 수있는 합리적으로 편리한 프리미티브를 제공하기 때문입니다.
병렬 처리에 대한 자세한 내용 :
병렬 처리는 매우 작은 규모 (예 : 프로세서의 명령어 수준 병렬 처리), 중간 규모 (예 : 멀티 코어 프로세서) 및 대규모 (예 : 고성능 컴퓨팅 클러스터)로 존재합니다. 멀티 코어 프로세서의 성장으로 인해 최근 몇 년 동안 소프트웨어 개발자가 더 많은 스레드 수준 병렬 처리를 노출해야한다는 압력이 증가했습니다. 병렬성은 의존 의 개념과 밀접하게 연결되어 있습니다. 종속성은 병렬 처리를 달성 할 수있는 범위를 제한합니다. 하나가 다른 작업에 의존하는 경우 두 작업을 병렬로 실행할 수 없습니다 (추론 무시).
프로그래머가 병렬성을 표현하는 데 사용하는 많은 패턴과 프레임 워크가 있습니다. 파이프 라인, 작업 풀, 데이터 구조에 대한 집계 작업 ( "병렬 배열").
상호 작용에 대한 자세한 내용 :
상호 작용을 수행하는 가장 기본적이고 일반적인 방법은 이벤트를 사용하는 것입니다 (예 : 이벤트 루프 및 핸들러 / 콜백). 간단한 작업의 경우 이벤트가 좋습니다. 이벤트로 더 복잡한 작업을 수행하려고하면 스택 리핑 (콜백 지옥, 일명 제어 반전)이 발생합니다. 이벤트에 질리면 생성기, 코 루틴 (Async / Await라고도 함) 또는 협력 스레드와 같은 더 이국적인 것을 시도 할 수 있습니다.
신뢰할 수있는 소프트웨어에 대한 애정을 위해 대화 형 작업이 필요한 경우 스레드를 사용하지 마십시오.
Curmudgeonliness
나는 Rob Pike의 "동시성은 병렬성이 아니라 더 낫다"라는 슬로건을 싫어합니다. 동시성은 병렬 처리보다 낫지도 나쁘지도 않습니다. 동시성에는 병렬성과 더 나은 / 나쁜 방식으로 비교할 수없는 상호 작용이 포함됩니다. "제어 흐름이 데이터보다 낫다"는 것과 같습니다.
전자 장치에서 직렬 및 병렬 은 회로의 실제 동작을 결정하는 정적 토폴로지 유형을 나타냅니다. 동시성이없는 경우 병렬 처리는 결정적 입니다.
동적 인 시간 관련 현상 을 설명하기 위해 순차 및 동시 라는 용어를 사용합니다 . 예를 들어, 특정 작업 시퀀스 (예 : 레시피) 를 통해 특정 결과를 얻을 수 있습니다 . 누군가와 이야기 할 때 우리는 일련의 단어를 생성합니다. 그러나 실제로는 다른 많은 프로세스가 동일한 순간에 발생하므로 특정 작업의 실제 결과와 일치 합니다. 많은 사람들이 동시에 말하고 있다면 동시 대화가 우리의 순서를 방해 할 수 있지만이 방해의 결과는 미리 알려지지 않았습니다. 동시성은 불확실성을 도입 합니다.
The serial/parallel and sequential/concurrent characterization are orthogonal. An example of this is in digital communication. In a serial adapter, a digital message is temporally (i.e. sequentially) distributed along the same communication line (eg. one wire). In a parallel adapter, this is divided also on parallel communication lines (eg. many wires), and then reconstructed on the receiving end.
Let us image a game, with 9 children. If we dispose them as a chain, give a message at the first and receive it at the end, we would have a serial communication. More words compose the message, consisting in a sequence of communication unities.
I like ice-cream so much. > X > X > X > X > X > X > X > X > X > ....
This is a sequential process reproduced on a serial infrastructure.
이제 아이들을 3 개의 그룹으로 나누는 이미지를 보겠습니다. 우리는 문구를 세 부분으로 나누고, 첫 번째는 왼쪽 줄의 자식에게, 두 번째는 중앙선의 자식에게줍니다.
I like ice-cream so much. > I like > X > X > X > .... > ....
> ice-cream > X > X > X > ....
> so much > X > X > X > ....
이것은 병렬 인프라 에서 재현 되는 순차 프로세스입니다 (여전히 부분적으로 직렬화 됨).
두 경우 모두 아이들 사이에 완벽한 의사 소통이 있다고 가정하면 결과가 미리 결정 됩니다.
귀하와 동시에 첫 번째 자녀와 대화하는 다른 사람이있는 경우 동시 프로세스가 제공됩니다 . 인프라에서 어떤 프로세스를 고려할지 모르기 때문에 최종 결과는 미리 결정되지 않습니다 .
Concurrency is the generalized form of parallelism. For example parallel program can also be called concurrent but reverse is not true.
Concurrent execution is possible on single processor (multiple threads, managed by scheduler or thread-pool)
Parallel execution is not possible on single processor but on multiple processors. (One process per processor)
Distributed computing is also a related topic and it can also be called concurrent computing but reverse is not true, like parallelism.
For details read this research paper Concepts of Concurrent Programming
I really like Paul Butcher's answer to this question (he's the writer of Seven Concurrency Models in Seven Weeks):
Although they’re often confused, parallelism and concurrency are different things. Concurrency is an aspect of the problem domain—your code needs to handle multiple simultaneous (or near simultaneous) events. Parallelism, by contrast, is an aspect of the solution domain—you want to make your program run faster by processing different portions of the problem in parallel. Some approaches are applicable to concurrency, some to parallelism, and some to both. Understand which you’re faced with and choose the right tool for the job.
I really liked this graphical representation from another answer - I think it answers the question much better than a lot of the above answers
Parallelism vs Concurrency When two threads are running in parallel, they are both running at the same time. For example, if we have two threads, A and B, then their parallel execution would look like this:
CPU 1: A ------------------------->
CPU 2: B ------------------------->
When two threads are running concurrently, their execution overlaps. Overlapping can happen in one of two ways: either the threads are executing at the same time (i.e. in parallel, as above), or their executions are being interleaved on the processor, like so:
CPU 1: A -----------> B ----------> A -----------> B ---------->
So, for our purposes, parallelism can be thought of as a special case of concurrency
Source: Another answer here
Hope that helps.
Concurrency can involve tasks run simultaneously or not (they can indeed be run in separate processors/cores but they can as well be run in "ticks"). What is important is that concurrency always refer to doing a piece of one greater task. So basically it's a part of some computations. You have to be smart about what you can do simultaneously and what not to and how to synchronize.
Parallelism means that you're just doing some things simultaneously. They don't need to be a part of solving one problem. Your threads can, for instance, solve a single problem each. Of course synchronization stuff also applies but from different perspective.
"Concurrency" is when there are multiple things in progress.
"Parallelism" is when concurrent things are progressing at the same time.
Examples of concurrency without parallelism:
- Multiple threads on a single core.
- Multiple messages in a Win32 message queue.
- Multiple
SqlDataReader
s on a MARS connection. - Multiple JavaScript promises in a browser tab.
Note, however, that the difference between concurrency and parallelism is often a matter of perspective. The above examples are non-parallel from the perspective of (observable effects of) executing your code. But there is instruction-level parallelism even within a single core. There are pieces of hardware doing things in parallel with CPU and then interrupting the CPU when done. GPU could be drawing to screen while you window procedure or event handler is being executed. The DBMS could be traversing B-Trees for the next query while you are still fetching the results of the previous one. Browser could be doing layout or networking while your Promise.resolve()
is being executed. Etc, etc...
So there you go. The world is as messy as always ;)
Concurrent programming regards operations that appear to overlap and is primarily concerned with the complexity that arises due to non-deterministic control flow. The quantitative costs associated with concurrent programs are typically both throughput and latency. Concurrent programs are often IO bound but not always, e.g. concurrent garbage collectors are entirely on-CPU. The pedagogical example of a concurrent program is a web crawler. This program initiates requests for web pages and accepts the responses concurrently as the results of the downloads become available, accumulating a set of pages that have already been visited. Control flow is non-deterministic because the responses are not necessarily received in the same order each time the program is run. This characteristic can make it very hard to debug concurrent programs. Some applications are fundamentally concurrent, e.g. web servers must handle client connections concurrently. Erlang is perhaps the most promising upcoming language for highly concurrent programming.
Parallel programming concerns operations that are overlapped for the specific goal of improving throughput. The difficulties of concurrent programming are evaded by making control flow deterministic. Typically, programs spawn sets of child tasks that run in parallel and the parent task only continues once every subtask has finished. This makes parallel programs much easier to debug. The hard part of parallel programming is performance optimization with respect to issues such as granularity and communication. The latter is still an issue in the context of multicores because there is a considerable cost associated with transferring data from one cache to another. Dense matrix-matrix multiply is a pedagogical example of parallel programming and it can be solved efficiently by using Straasen's divide-and-conquer algorithm and attacking the sub-problems in parallel. Cilk is perhaps the most promising language for high-performance parallel programming on shared-memory computers (including multicores).
Copied from my answer: https://stackoverflow.com/a/3982782
Parallelism: Having multiple threads do similar task which are independent of each other in terms of data and resource that they require to do so. Eg: Google crawler can spawn thousands of threads and each thread can do it's task independently.
Concurrency: Concurrency comes into picture when you have shared data, shared resource among the threads. In a transactional system this means you have to synchronize the critical section of the code using some techniques like Locks, semaphores, etc.
The simplest and most elegant way of understanding the two in my opinion is this. Concurrency allows interleaving of execution and so can give the illusion of parallelism. This means that a concurrent system can run your Youtube video alongside you writing up a document in Word, for example. The underlying OS, being a concurrent system, enables those tasks to interleave their execution. Because computers execute instructions so quickly, this gives the appearance of doing two things at once.
Parallelism is when such things really are in parallel. In the example above, you might find the video processing code is being executed on a single core, and the Word application is running on another. Note that this means that a concurrent program can also be in parallel! Structuring your application with threads and processes enables your program to exploit the underlying hardware and potentially be done in parallel.
Why not have everything be parallel then? One reason is because concurrency is a way of structuring programs and is a design decision to facilitate separation of concerns, whereas parallelism is often used in the name of performance. Another is that some things fundamentally cannot fully be done in parallel. An example of this would be adding two things to the back of a queue - you cannot insert both at the same time. Something must go first and the other behind it, or else you mess up the queue. Although we can interleave such execution (and so we get a concurrent queue), you cannot have it parallel.
Hope this helps!
(I'm quite surprised such a fundamental question is not resolved correctly and neatly for years...)
In short, both concurrency and parallelism are properties of computing.
As of the difference, here is the explanation from Robert Harper:
The first thing to understand is parallelism has nothing to do with concurrency. Concurrency is concerned with nondeterministic composition of programs (or their components). Parallelism is concerned with asymptotic efficiency of programs with deterministic behavior. Concurrency is all about managing the unmanageable: events arrive for reasons beyond our control, and we must respond to them. A user clicks a mouse, the window manager must respond, even though the display is demanding attention. Such situations are inherently nondeterministic, but we also employ pro forma nondeterminism in a deterministic setting by pretending that components signal events in an arbitrary order, and that we must respond to them as they arise. Nondeterministic composition is a powerful program structuring idea. Parallelism, on the other hand, is all about dependencies among the subcomputations of a deterministic computation. The result is not in doubt, but there are many means of achieving it, some more efficient than others. We wish to exploit those opportunities to our advantage.
They can be sorts of orthogonal properties in programs. Read this blog post for additional illustrations. And this one discussed slightly more on difference about components in programming, like threads.
Note that threading or multitasking are all implementations of computing serving more concrete purposes. They can be related to parallelism and concurrency, but not in an essential way. Thus they are hardly good entries to start the explanation.
One more highlight: (physical) "time" has almost nothing to do with the properties discussed here. Time is just a way of implementation of the measurement to show the significance of the properties, but far from the essence. Think twice the role of "time" in time complexity - which is more or less similar, even the measurement is often more significant in that case.
Great, let me take an scenario to show what I understand. suppose there're 3 kids named: A, B, C. A and B talk, C listen. For A and B, they are parallel: A: I am A. B: I am B.
But for C, his brain must take the concurrent process to listen A and B, it maybe: I am I A am B.
Concurrency simple means more than one tasks are running (not necessary in parallel). For example assumer we have 3 tasks then at any moment of time: more than one may be running or all may be running at same time.
Parallelism mean they are literally running in parallel. So in that case all three must be running at same time.
Pike's notion of "concurrency" is an intentional design and implementation decision. A concurrent-capable program design may or may not exhibit behavioral "parallelism"; it depends upon the runtime environment.
You don't want parallelism exhibited by a program that wasn't designed for concurrency. :-) But to the extent that it's a net gain for the relevant factors (power consumption, performance, etc.), you want a maximally-concurrent design so that the host system can parallelize its execution when possible.
Pike's Go programming language illustrates this in the extreme: his functions are all threads that can run correctly concurrently, i.e. calling a function always creates a thread that will run in parallel with the caller if the system is capable of it. An application with hundreds or even thousands of threads is perfectly ordinary in his world. (I'm no Go expert, that's just my take on it.)
Explanation from this source was helpful for me:
Concurrency is related to how an application handles multiple tasks it works on. An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently).
Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel.
As you can see, an application can be concurrent, but not parallel. This means that it processes more than one task at the same time, but the tasks are not broken down into subtasks.
An application can also be parallel but not concurrent. This means that the application only works on one task at a time, and this task is broken down into subtasks which can be processed in parallel.
또한 응용 프로그램은 동시 또는 병렬이 될 수 없습니다. 즉, 한 번에 하나의 작업에서만 작동하며 병렬 실행을 위해 작업이 하위 작업으로 분할되지 않습니다.
마지막으로, 응용 프로그램은 동시에 여러 작업에서 작동하고 병렬 실행을 위해 각 작업을 하위 작업으로 분할한다는 점에서 동시 및 병렬이 될 수도 있습니다. 그러나이 시나리오에서는 컴퓨터의 CPU가 동시성 또는 병렬성만으로 합리적으로 바쁘기 때문에 동시성과 병렬성의 일부 이점이 손실 될 수 있습니다. 이를 결합하면 성능이 약간만 향상되거나 성능이 저하 될 수 있습니다.
'programing tip' 카테고리의 다른 글
grep을 사용하여 Linux에서 파일 이름 만 표시하려면 어떻게해야합니까? (0) | 2020.09.28 |
---|---|
Java 클래스 경로 내의 디렉토리에있는 모든 jar 포함 (0) | 2020.09.28 |
인라인 CSS에서 a : hover를 작성하는 방법은 무엇입니까? (0) | 2020.09.28 |
왼쪽에 0이있는 정수를 어떻게 채울 수 있습니까? (0) | 2020.09.28 |
Java에서 현재 스택 추적 가져 오기 (0) | 2020.09.28 |