search
HomeBackend DevelopmentPython TutorialExample to explain golang simulation implementation of semaphore with timeout

This article mainly introduces to you the relevant information about golang simulation implementation of semaphore with timeout. The article introduces it in detail through the example code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn with the editor below.

Preface

I am writing a project recently and need to use semaphores to wait for some resources to complete, but the maximum wait is N milliseconds. Before looking at the main text of this article, let's first look at the implementation method in C language.

In C language, there is the following API to implement semaphore waiting with timeout:


SYNOPSIS
  #include <pthread.h>
 
  int
  pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);

Then check golang After reading the document, I found that semaphore with timeout is not implemented in golang. The official document is here.

Principle

My business scenario is this: I have a cache dictionary, when multiple users request a non-existent key At this time, only one request will penetrate to the backend, and all users will have to queue up and wait for this request to be completed, or return with a timeout.

How to achieve it? In fact, if you think about the principle of cond for a moment, you can simulate a cond with timeout.

In golang, to implement "suspend waiting" and "timeout return" at the same time, you generally need to use select case syntax. One case waits for blocked resources, and one case waits for a timer. This is very certain. .

Originally blocked resources should be notified of completion through the mechanism of condition variables. Since it is decided to use select case here, it is natural to think of using channel to replace this completion notification.

The next problem is that many requesters come to obtain this resource concurrently, but the resource is not ready yet, so everyone has to queue and hang up, waiting for the resource to be completed, and notify everyone when the resource is completed.

So, it is natural to create a queue for this resource. Each requester creates a chan, puts the chan in the queue, and then selects the case to wait for the notification of the chan. On the other end, after the resource is completed, it traverses the queue and notifies each chan.

The last problem is that only the first requester can penetrate the request to the backend, and subsequent requesters should not penetrate repeated requests. This can be determined by judging whether there is this key in the cache as the first time. condition, and flag bit init to determine whether the requester should queue.

My scenario

The above is the idea, and the following is the implementation of my business scenario.


func (cache *Cache) Get(key string, keyType int) *string {
 if keyType == KEY_TYPE_DOMAIN {
 key = "#" + key
 } else {
 key = "=" + key
 }
 
 cache.mutex.Lock()
 item, existed := cache.dict[key]
 if !existed {
 item = &cacheItem{}
 item.key = &key
 item.waitQueue = list.New()
 cache.dict[key] = item
 }
 cache.mutex.Unlock()
 
 conf := config.GetConfig()
 
 lastGet := getCurMs()
 
 item.mutex.Lock()
 item.lastGet = lastGet
 if item.init { // 已存在并且初始化
 defer item.mutex.Unlock()
 return item.value
 }
 
 // 未初始化,排队等待结果
 wait := waitItem{}
 wait.wait_chan = make(chan *string, 1)
 item.waitQueue.PushBack(&wait)
 item.mutex.Unlock()
 
 // 新增key, 启动goroutine获取初始值
 if !existed {
 go cache.initCacheItem(item, keyType)
 }
 
 timer := time.NewTimer(time.Duration(conf.Cache_waitTime) * time.Millisecond)
 
 var retval *string = nil
 
 // 等待初始化完成
 select {
 case retval = <- wait.wait_chan:
 case <- timer.C:
 }
 return retval
}

Briefly describe the whole process:

  • First lock the dictionary. If the key does not exist, explain I am the first requester, and I will create the value corresponding to this key, but init=false means that it is being initialized. Finally, release the dictionary lock.

  • Next, lock the key and judge that it has been initialized, then return the value directly. Otherwise, create a chan and put it into the waitQueue waiting queue. Finally, release the key lock.

  • Next, if it is the first requester, it will penetrate the request to the backend (initiate a network call in an independent coroutine).

  • Now, create a timer for timeout.

  • Finally, regardless of whether it is the first requester of the key or a concurrent requester during initialization, they are all completed by waiting for the result of the select case timeout.

In the initCacheItem function, the data has been obtained successfully


 // 一旦标记为init, 后续请求将不再操作waitQueue
 item.mutex.Lock()
 item.value = newValue
 item.init = true
 item.expire = expire
 item.mutex.Unlock()
 
 // 唤醒所有排队者
 waitQueue := item.waitQueue
 for elem := waitQueue.Front(); elem != nil; elem = waitQueue.Front() {
 wait := elem.Value.(*waitItem)
 wait.wait_chan <- newValue
 waitQueue.Remove(elem)
 }
  • First, lock the key and mark it init=true, assign value, and release the lock. Subsequent requests can be returned immediately without queuing.

  • After that, because init=true has been marked, there are no requests to modify waitQueue at this moment, so there is no need to lock, traverse the queue directly, and notify each chan in it.

Finally

This achieves the condition variable effect with timeout. In fact, my scene is a broadcast Cond example, you can refer to the ideas to achieve the effect you want, learn and use it.

The above is the detailed content of Example to explain golang simulation implementation of semaphore with timeout. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor