스레드 셀

스레드 셀 (Thread Cells)

스레드 셀(thread cell)은 스레드에 특화된 값을 담아요. 즉 스레드마다 특정한 값을 가지지만, 서로 다른 스레드에 대해서는 서로 다른 값을 가질 수 있어요. 스레드 셀은 모든 기존 스레드에 사용되는 기본 값으로 만들어져요. thread-cell-set!으로 셀 내용을 바꾸면 오직 현재 스레드에 대해서만 셀 값이 변해요. 마찬가지로 thread-cell-ref는 현재 스레드에 특화된 셀 값을 얻어와요.

출처: Racket Reference

본문

스레드 셀의 값은 보존(preserved)될 수 있어요. 보존된다는 뜻은, 새 스레드가 만들어질 때 새 스레드에 대한 셀의 초기 값이 생성 스레드의 현재 값과 같다는 뜻이에요. 스레드 셀이 비보존(non-preserved)이면, 새로 만든 스레드에 대한 셀의 초기 값은 기본 값(셀을 만들 때 제공한 값)이에요.

현재 스레드 안에서 모든 보존 스레드 셀의 현재 값은 current-preserved-thread-cell-values로 포착할 수 있어요. 포착한 값들의 집합은 current-preserved-thread-cell-values를 다시 호출해서 현재 스레드에 명령적으로(imperatively) 설치할 수 있어요. 포착하는 스레드와 복원하는 스레드는 달라도 돼요.

(thread-cell? v) → boolean?
  v : any/c

v가 스레드 셀이면 #t, 아니면 #f를 반환해요.

(make-thread-cell v [preserved?]) → thread-cell?
  v : any/c
  preserved? : any/c = #f

새 스레드 셀을 만들어 반환해요. 처음에는 v가 모든 스레드에 대한 셀의 값이에요. preserved?가 참이면, 새로 만든 스레드에 대한 셀의 초기 값은 생성 스레드가 그 셀에 대해 가지는 값이고, 그렇지 않으면 앞으로 모든 스레드에서 셀 값이 처음에는 v예요.

(thread-cell-ref cell) → any
  cell : thread-cell?

현재 스레드에 대한 cell의 현재 값을 반환해요.

(thread-cell-set! cell v) → any
  cell : thread-cell?
  v : any/c

현재 스레드에 대한 cell의 값을 v로 설정해요.

예제를 볼게요.

> (define cnp (make-thread-cell '(nerve) #f))
> (define cp (make-thread-cell '(cancer) #t))
> (thread-cell-ref cnp)
'(nerve)
> (thread-cell-ref cp)
'(cancer)
> (thread-cell-set! cnp '(nerve nerve))
> (thread-cell-set! cp '(cancer cancer))
> (thread-cell-ref cnp)
'(nerve nerve)
> (thread-cell-ref cp)
'(cancer cancer)
> (define ch (make-channel))
> (thread (lambda ()
           (channel-put ch (thread-cell-ref cnp))
           (channel-put ch (thread-cell-ref cp))
           (channel-get ch)
           (channel-put ch (thread-cell-ref cp))))
#<thread>
> (channel-get ch)
'(nerve)
> (channel-get ch)
'(cancer cancer)
> (thread-cell-set! cp '(cancer cancer cancer))
> (thread-cell-ref cp)
'(cancer cancer cancer)
> (channel-put ch 'ok)
> (channel-get ch)
'(cancer cancer)
(current-preserved-thread-cell-values) → thread-cell-values?
(current-preserved-thread-cell-values thread-cell-vals) → void?
  thread-cell-vals : thread-cell-values?

인자 없이 호출하면, 이 프로시저는 (현재 스레드 안에서) 모든 보존 스레드 셀의 현재 값을 나타내는 thread-cell-vals를 만들어내요.

current-preserved-thread-cell-values에 대한 이전 호출로 만들어진 thread-cell-vals를 인자로 호출하면, (현재 스레드 안에서) 모든 보존 스레드 셀의 값이 thread-cell-vals에 포착된 값으로 설정돼요. 만약 thread-cell-vals가 만들어진 이후에 보존 스레드 셀이 만들어졌다면, 그 스레드 셀의 현재 스레드에 대한 값은 초기 값으로 되돌아가요.

(thread-cell-values? v) → boolean?
  v : any/c

vcurrent-preserved-thread-cell-values가 만들어낸 스레드 셀 값의 집합이면 #t, 아니면 #f를 반환해요.

더 알아보기

  • 파라미터(Parameters): 스레드 셀에 연속 표시를 결합한 방식
  • The Racket Guide의 스레드 장