|
MultiThread 프로그램 작업시 Thread T1, 과 Thread T2를 동기화 시킬 수 있는 방법
동기화는 왜할까요?
T1 이 변수 i 를 1씩 증가 시키고 T2가 그 증가된 변수를 출력 한다고 하면
T1 :
for(i=1; i<10 i++);
T2 :
printf("%d",i);
동기화를 안시키면
결과가 1 , 2 , 10,10,10,10 ...
즉 연산이 빨리 되는놈이 다 해버리고 느린놈이 뒷북을 치죠..
그러면 동기화를 시키게 되면
T1 -> 나 한개 증가 했어
T2 -> 그래 그러면 출력할께, 출력했어
이런식이기때문에.
1,2,3,4,5,6,7,8,9 를 제대로 찍을 수 있죠....
이런 동기화 방법엔
1. Critical Section - Enter Critial 과 ExitCritcal 에 들어 있는 코드 실행중
다른 모든 Thread들의 접근을 막는다.
2. MuTex - CS 와 비슷하지만 느리다(저도 이것은 잘 모릅니다.)
3. 세마포어 - 세마포어를 주고 받으며 프로그램을 동기화 한다.
가 있습니다.
그러면 Synchronize 동기화는 도대체 무엇인가? 조금 엉터리 해석이지만...
도움말에 의하면
Executes a method call within the main VCL thread.
VCL Thread 안에서 method를 호출을 실행한다.
typedef void __fastcall (__closure *TThreadMethod)(void);
void __fastcall Synchronize(TThreadMethod &Method);
Description
Synchronize causes the call specified by Method to be executed using the main
VCL thread, thereby avoiding multi-thread conflicts.
Synchronize는 Method에 의해서 지정된 호출이 main VCL Thread에서 실행될 수 있게 해줍니다.
따라서 multi-thread의 충돌을 피하게 해준다.
If you are unsure whether a method call is thread-safe, call it
from within the main VCL thread by passing it to the Synchronize method.
만약 당신이 호출하는 method 가 thread에 안전한지 자신이 없으면 그 method를 Synchronize
method 를 통해서 VCL thread에서 호출 하세요
Execution of the thread is suspended while Method is executing in the main VCL thread.
Method 가 main VCL thread 에서 실행되는동안 그 Thread의 실행은 중지 됩니다.
Note: You can also protect unsafe methods using critical sections or the multi-read exclusive-write synchronizer.
주의 : CS나 (읽는것은 누구나 쓰는것은 혼자만) 등의 동기화 방법을 통해서도 thread unsafe method 를 보호할 수 있습니다.
결론... 즉..두 쓰레드를 동기화시 CS, Mutex, Semaphore를 사용해도 되지만 자신이 없으면 VCL 에 모두 맡겨달라.. 라는 얘깁니다. Synchronize 를 써서..
그러면 어떻게 할것인가 일다 Synchoronize 를 무조건 쓰십시오. 그리고 동기화 시에 자기가 원하는 방법대로 Semaphore 등을 사용하십시요.. 그럼..
|