2016-09-30 7 views
1

나는 내가 칠 수있는 횟수를 제한하려면, 내 현재의 구현은 웹 사이트를 얻기 위해 10 이동 루틴을 사용제한 횟수 핑 호스트 이름 매 초마다

이동 배울 웹 크롤러를 쓰고 있어요 매 초마다 호스트 이름.

이 작업을 수행하는 가장 좋은 (스레드로부터 안전 한) 접근 방식은 무엇입니까?

+1

코드 예를 게시하십시오. –

+1

참조 : Golang에서 초당 여러 번 명령을 실행하는 방법 : http://stackoverflow.com/questions/39385883/how-do-i-execute-commands-many-many 타격 - 당 - 당 - 골간 –

답변

1

channel은 조정할 때 사용할 수있는 동시 동기화 메커니즘을 제공합니다. time.Ticker과 함게 하나를 사용하여 주어진 수의 함수 호출을 주기적으로 디스패치 할 수 있습니다.

// A PeriodicResource is a channel that is rebuffered periodically. 
type PeriodicResource <-chan bool 

// The NewPeriodicResourcePool provides a buffered channel that is filled after the 
// given duration. The size of the channel is given as count. This provides 
// a way of limiting an function to count times per duration. 
func NewPeriodicResource(count int, reset time.Duration) PeriodicResource { 
    ticker := time.NewTicker(reset) 
    c := make(chan bool, count) 

    go func() { 
     for { 
      // Await the periodic timer 
      <-ticker.C 

      // Fill the buffer 
      for i := len(c); i < count; i++ { 
       c <- true 
      } 
     } 
    }() 

    return c 
} 

단일 이동 루틴은 각 티커 이벤트를 기다리고 최대 용량까지 버퍼링 된 채우기를 시도합니다. 소비자가 버퍼를 고갈시키지 않으면 연속적인 틱은 그것을 다시 채 웁니다. 채널을 사용하여 n 번/시간 ()을 동 기적으로 동시에 수행 할 수 있습니다. 예를 들어, doSomething()을 초당 5 회 이상 호출 할 수 있습니다.

r := NewPeriodicResource(5, time.Second) 
for { 
     // Attempt to deque from the PeriodicResource 
     <-r 

     // Each call is synchronously drawing from the periodic resource 
     doSomething() 
} 

물론, 같은 채널은 당 가장 다섯 과정에서 팬 밖으로 것 go doSomething()를 호출하는 데 사용할 수 있습니다.