// pollRxQueue repeatedly polls an Rx queue for interrupts.
160243
func pollRxQueue(memif *Memif, queueID uint8) {
	defer memif.wg.Done()

	log.WithFields(logger.Fields{
		"ifName":   memif.IfName,
		"queue-ID": queueID,
	}).Debug("Started queue interrupt polling.")

	var qfd C.int
	errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
	err := getMemifError(int(errCode))
	if err != nil {
		log.WithField("err", err).Error("memif_get_queue_efd() failed")
		return
	}

	// Create epoll file descriptor.
	var event [1]syscall.EpollEvent
	epFd, err := syscall.EpollCreate1(0)
	if err != nil {
		log.WithField("err", err).Error("epoll_create1() failed")
		return
	}
	defer syscall.Close(epFd)

	// Add Rx queue interrupt file descriptor.
	event[0].Events = syscall.EPOLLIN
	event[0].Fd = int32(qfd)
	if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
		log.WithField("err", err).Error("epoll_ctl() failed")
		return
	}

	// Add file descriptor used to stop this go routine.
	event[0].Events = syscall.EPOLLIN
	event[0].Fd = int32(memif.stopQPollFd)
	if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
		log.WithField("err", err).Error("epoll_ctl() failed")
		return
	}

	// Poll for interrupts.
	for {
		_, err := syscall.EpollWait(epFd, event[:], -1)
		if err != nil {
			log.WithField("err", err).Error("epoll_wait() failed")
			return
		}

		// Handle Rx Interrupt.
		if event[0].Fd == int32(qfd) {
			// Consume the interrupt event.
			buf := make([]byte, 8)
			_, err = syscall.Read(int(qfd), buf[:])
			if err != nil {
				log.WithField("err", err).Warn("read() failed")
			}

			// Send signal to memif-global interrupt channel.
			select {
			case memif.intCh <- queueID:
				break
			default:
				break
			}

			// Send signal to queue-specific interrupt channel.
			select {
			case memif.queueIntCh[queueID] <- struct{}{}:
				break
			default:
				break
			}
		}

		// Stop the go routine if requested.
		if event[0].Fd == int32(memif.stopQPollFd) {
			log.WithFields(logger.Fields{
				"ifName":   memif.IfName,
				"queue-ID": queueID,
			}).Debug("Stopped queue interrupt polling.")
			return
		}
	}
}
1245898
func pollEvents() {
	defer context.wg.Done()
	for {
		errCode := C.memif_poll_event(C.int(-1))
		err := getMemifError(int(errCode))
		if err == ErrPollCanceled {
			return
		}
	}
}
1132424
func (pq *BlockPriorityQueue) Reheap() {
	pq.mtx.Lock()
	defer pq.mtx.Unlock()

	pq.needsReheap = false
	heap.Init(pq)
}
696317
func (r *rpcHandler) blockingRPC(opts *blockingOptions) error {
	ctx := context.Background()
	var cancel context.CancelFunc
	var state *state.StateStore

	// Fast path non-blocking
	if opts.queryOpts.MinQueryIndex == 0 {
		goto RUN_QUERY
	}

	// Restrict the max query time, and ensure there is always one
	if opts.queryOpts.MaxQueryTime > maxQueryTime {
		opts.queryOpts.MaxQueryTime = maxQueryTime
	} else if opts.queryOpts.MaxQueryTime <= 0 {
		opts.queryOpts.MaxQueryTime = defaultQueryTime
	}

	// Apply a small amount of jitter to the request
	opts.queryOpts.MaxQueryTime += lib.RandomStagger(opts.queryOpts.MaxQueryTime / structs.JitterFraction)

	// Setup a query timeout
	ctx, cancel = context.WithTimeout(context.Background(), opts.queryOpts.MaxQueryTime)
	defer cancel()

RUN_QUERY:
	// Update the query meta data
	r.setQueryMeta(opts.queryMeta)

	// Increment the rpc query counter
	metrics.IncrCounter([]string{"nomad", "rpc", "query"}, 1)

	// We capture the state store and its abandon channel but pass a snapshot to
	// the blocking query function. We operate on the snapshot to allow separate
	// calls to the state store not all wrapped within the same transaction.
	state = r.fsm.State()
	abandonCh := state.AbandonCh()
	snap, _ := state.Snapshot()
	stateSnap := &snap.StateStore

	// We can skip all watch tracking if this isn't a blocking query.
	var ws memdb.WatchSet
	if opts.queryOpts.MinQueryIndex > 0 {
		ws = memdb.NewWatchSet()

		// This channel will be closed if a snapshot is restored and the
		// whole state store is abandoned.
		ws.Add(abandonCh)
	}

	// Block up to the timeout if we didn't see anything fresh.
	err := opts.run(ws, stateSnap)

	// Check for minimum query time
	if err == nil && opts.queryOpts.MinQueryIndex > 0 && opts.queryMeta.Index <= opts.queryOpts.MinQueryIndex {
		if err := ws.WatchCtx(ctx); err == nil {
			goto RUN_QUERY
		}
	}
	return err
}
841223
func (c *asyncClient) Renamenx(arg0 string, arg1 string) (result FutureBool, err Error) {
	arg0bytes := []byte(arg0)
	arg1bytes := []byte(arg1)

	var resp *PendingResponse
	resp, err = c.conn.QueueRequest(&RENAMENX, [][]byte{arg0bytes, arg1bytes})
	if err == nil {
		result = resp.future.(FutureBool)
	}
	return result, err

}
157306
func (q *TransmitLimitedQueue) NumQueued() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return q.lenLocked()
}
892991
func (poller *fdPoller) wake() error {
	buf := make([]byte, 1)
	n, errno := unix.Write(poller.pipe[1], buf)
	if n == -1 {
		if errno == unix.EAGAIN {
			// Buffer is full, poller will wake.
			return nil
		}
		return errno
	}
	return nil
}
140988
func (p *prober) copyResultRLocked(ip string) *models.PathStatus {
	status := p.results[ipString(ip)]
	if status == nil {
		return nil
	}

	result := &models.PathStatus{
		IP: ip,
	}
	paths := map[**models.ConnectivityStatus]*models.ConnectivityStatus{
		&result.Icmp: status.Icmp,
		&result.HTTP: status.HTTP,
	}
	for res, value := range paths {
		if value != nil {
			*res = &*value
		}
	}
	return result
}
469060
func (c *client) QueuePause() error {
	uri := fmt.Sprintf(pathQueue, c.addr)
	err := c.delete(uri)
	return err
}
904052
func (q *LinkedBlockingDeque) PollFirst() (e interface{}) {
	q.lock.Lock()
	result := q.unlinkFirst()
	q.lock.Unlock()
	return result
}
765964
func (f *fragment) handleMutex(rowID, columnID uint64) error {
	if existingRowID, found, err := f.mutexVector.Get(columnID); err != nil {
		return errors.Wrap(err, "getting mutex vector data")
	} else if found && existingRowID != rowID {
		if _, err := f.unprotectedClearBit(existingRowID, columnID); err != nil {
			return errors.Wrap(err, "clearing mutex value")
		}
	}
	return nil
}
433621
func (f *Fetcher) processQueue() {
loop:
	for v := range f.q.ch {
		if v == nil {
			// Special case, when the Queue is closed, a nil command is sent, use this
			// indicator to check for the closed signal, instead of looking on every loop.
			select {
			case <-f.q.closed:
				// Close signal, exit loop
				break loop
			default:
				// Keep going
			}
		}
		select {
		case <-f.q.cancelled:
			// queue got cancelled, drain
			continue
		default:
			// go on
		}

		// Get the URL to enqueue
		u := v.URL()

		// Check if a channel is already started for this host
		f.mu.Lock()
		in, ok := f.hosts[u.Host]
		if !ok {
			// Start a new channel and goroutine for this host.

			var rob *url.URL
			if !f.DisablePoliteness {
				// Must send the robots.txt request.
				rob = u.ResolveReference(robotsTxtParsedPath)
			}

			// Create the infinite queue: the in channel to send on, and the out channel
			// to read from in the host's goroutine, and add to the hosts map
			var out chan Command
			in, out = make(chan Command, 1), make(chan Command, 1)
			f.hosts[u.Host] = in
			f.mu.Unlock()
			f.q.wg.Add(1)
			// Start the infinite queue goroutine for this host
			go sliceIQ(in, out)
			// Start the working goroutine for this host
			go f.processChan(out, u.Host)

			if !f.DisablePoliteness {
				// Enqueue the robots.txt request first.
				in <- robotCommand{&Cmd{U: rob, M: "GET"}}
			}
		} else {
			f.mu.Unlock()
		}
		// Send the request
		in <- v

		// Send debug info, but do not block if full
		f.dbgmu.Lock()
		if f.debugging {
			f.mu.Lock()
			select {
			case f.dbg <- &DebugInfo{len(f.hosts)}:
			default:
			}
			f.mu.Unlock()
		}
		f.dbgmu.Unlock()
	}

	// Close all host channels now that it is impossible to send on those. Those are the `in`
	// channels of the infinite queue. It will then drain any pending events, triggering the
	// handlers for each in the worker goro, and then the infinite queue goro will terminate
	// and close the `out` channel, which in turn will terminate the worker goro.
	f.mu.Lock()
	for _, ch := range f.hosts {
		close(ch)
	}
	f.hosts = make(map[string]chan Command)
	f.mu.Unlock()

	f.q.wg.Done()
}
83128
func (w *WorkerConfig) scheduler() {
	pollSets := []string{w.nsKey("retry"), w.nsKey("schedule")}

	for _ = range time.Tick(w.PollInterval) {
		w.RLock() // don't let quitHandler() stop us in the middle of a run
		conn := w.RedisPool.Get()
		now := fmt.Sprintf("%f", timeFloat(time.Now()))
		for _, set := range pollSets {
			conn.Send("MULTI")
			conn.Send("ZRANGEBYSCORE", set, "-inf", now)
			conn.Send("ZREMRANGEBYSCORE", set, "-inf", now)
			res, err := redis.Values(conn.Do("EXEC"))
			if err != nil {
				w.handleError(err)
				continue
			}

			for _, msg := range res[0].([]interface{}) {
				parsedMsg := &struct {
					Queue string `json:"queue"`
				}{}
				msgBytes := msg.([]byte)
				err := json.Unmarshal(msgBytes, parsedMsg)
				if err != nil {
					w.handleError(err)
					continue
				}
				if _, err = conn.Do("RPUSH", w.nsKey("queue:"+parsedMsg.Queue), msgBytes); err != nil {
					w.handleError(err)
				}
			}
		}
		conn.Close()
		w.RUnlock()
	}
}
624388
func (cli *socketClient) queueRequest(req *types.Request) *ReqRes {
	reqres := NewReqRes(req)

	// TODO: set cli.err if reqQueue times out
	cli.reqQueue <- reqres

	// Maybe auto-flush, or unset auto-flush
	switch req.Value.(type) {
	case *types.Request_Flush:
		cli.flushTimer.Unset()
	default:
		cli.flushTimer.Set()
	}

	return reqres
}
1052197
func (rw LeveledRWMutex) RUnlock(lockState *LockState) {
	err := lockState.doUnlock(rw.level, readExclusion, rw.rwLocker.RLocker())
	if err != nil {
		panic(err)
	}
}
1206302
func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (queue *Queue, err error) {
	redisClient := redis.NewClient(&redis.Options{
		Addr:     redisHost + ":" + redisPort,
		Password: redisPassword,
		DB:       redisDB,
	})
	defer redisClient.Close()

	isMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()
	if err != nil {
		return nil, err
	}
	if !isMember {
		return nil, fmt.Errorf("queue with this name doesn't exist")
	}

	return newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil
}
902895
func (pq *BlockPriorityQueue) Pop() interface{} {
	n := pq.Len()
	old := pq.bh
	block := old[n-1]
	block.heapIdx = -1
	pq.bh = old[0 : n-1]
	return block
}