Git Product home page Git Product logo

semaphore's Introduction

๐Ÿšฆ Semaphore

Semaphore provides a simple POSIX-style implementation of semaphores. Internally it uses buffered channels, but the exposed methods should be familiar to all C programmers.

Install

You can install this library using go get -u github.com/ChrisGora/semaphore.

Basic Usage

Creating a new semaphore

semaphore.Init(max, value) takes a maximum value and initial value for the new semaphore.

maxValue := 3
initValue := 0

sem := semaphore.Init(maxValue, initValue)

Wait / Pend / P

To decrease the value of the semaphore (also known as waiting, pending, etc.):

sem.Wait()

Post / Signal / V

To increase the value of the semaphore (also known as posting, signalling, etc.):

sem.Post()

Example Usage

Producer-Consumer

The producer-consumer problem can be solved with the semaphores and Go's mutexes in the following way:

func producer(buffer *buffer, spaceAvailable, workAvailable semaphore.Semaphore, mutex *sync.Mutex) {
	for {
		spaceAvailable.Wait()
		mutex.Lock()
		buffer.put(1)
		mutex.Unlock()
		workAvailable.Post()
	}
}

func consumer(buffer *buffer, spaceAvailable, workAvailable semaphore.Semaphore, mutex *sync.Mutex) {
	for {
		workAvailable.Wait()
		mutex.Lock()
		_ = buffer.get()
		mutex.Unlock()
		spaceAvailable.Post()
	}
}

semaphore's People

Contributors

chrisgora avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.