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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software