• Stars
    star
    102
  • Rank 325,035 (Top 7 %)
  • Language
    Objective-C
  • Created over 11 years ago
  • Updated over 11 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Thin API and concept on top of libdispatch (aka Grand Central Dispatch) for Cocoa Objective-C code.

Lazy dispatcher

A very thin API + concepts on top of libdispatch (aka Grand Central Dispatch) for Cocoa Objective-C code.

I'm a lazy person and so it hurts me when I have to write so much to do such common things as to schedule various blocks of code in various dispatch queues. This little thing lets me write less code with the added bonus of making the result more readable.

Example

First, using vanilla libdispatch:

dispatch_queue_t parentQueue = dispatch_get_current_queue();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  NSLog(@"Block #1 on queue '%s' (parentQueue: '%s')",
        dispatch_queue_get_label(dispatch_get_current_queue()),
        dispatch_queue_get_label(parentQueue));
  
  dispatch_queue_t parentQueue2 = dispatch_get_current_queue();
  dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"Block #2 on queue '%s'",
          dispatch_queue_get_label(dispatch_get_current_queue()));
    
    dispatch_async(parentQueue2, ^{
      NSLog(@"Block #3 on queue '%s'",
            dispatch_queue_get_label(dispatch_get_current_queue()));
      exit(0);
    });
  });
});

Now, with LazyDispatch:

sched_background ^(DQueue parentQueue){
  NSLog(@"Block #1 on queue '%s' (parentQueue: '%s')",
        DQueueID(__queue), DQueueID(parentQueue));

  sched_main ^(DQueue parentQueue){
    NSLog(@"Block #2 on queue '%s'", DQueueID(__queue));

    sched(parentQueue) ^{
      NSLog(@"Block #3 on queue '%s'", DQueueID(__queue));
    };
  };
};
Block #1 on queue 'com.apple.root.default-priority' (parentQueue: 'com.apple.main-thread')
Block #2 on queue 'com.apple.main-thread'
Block #3 on queue 'com.apple.root.default-priority'

See. Way simpler yet same performance as no actual overhead is added. We just rephrased things to be a little more readable.

Wow! I can haz so much fun nows!

There are also timers. We love them timers, don't we?!

sched_delay(1, ^{
  NSLog(@"Delayed block executed after one second");
});

Just like e.g. JavaScript, timers can be cancelled:

DTimer timer = sched_interval(13.37, ^{
  NSLog(@"Delayed block sez hi");
});
//...
DTimerStop(timer);

API

Types

  • DQueue β€” A dispatch queue (alias for dispatch_queue_t)
  • DBlock β€” A block (alias for dispatch_block_t)
  • DTimer β€” A timer (alias for dispatch_source_t)

Special variables

  • __queue β†’ DQueue β€” The current queue
  • __main_queue β†’ DQueue β€” The main queue

Keyword expressions

sched_background ^([DQueue parentQueue]) β†’ block

Schedules a block in the background queue. The block can optionally accept an argument which will be the queue from which sched_background was called. The result of the expression is the block itself.

Useful for invoking callbacks and returning control to the same queue, e.g:

- (void)doSomethingFunkyWithCallback:(DBlock)callback {
  sched_background ^(DQueue parentQueue){
    // work work work ...
    sched(parentQueue) callback;
  };
}

sched_main ^([DQueue parentQueue]) β†’ block

Schedules a block in the main queue. The block can optionally accept an argument which will be the queue from which sched_main was called. The result of the expression is the block itself.

sched(DQueue queue) ^([DQueue parentQueue]) β†’ block

Schedules a block in a queue. The block can optionally accept an argument which will be the queue from which sched was called. The result of the expression is the block itself.

Functions

const char* DQueueID(DQueue queue)

Access the human-readable identifier of queue (its "label")

DTimer sched_delay(NSTimeInterval delay, ^([DTimer[, DQueue]]))

Schedule a block in the current queue to execute after delay seconds. You can call DTimerStop on the DTimer object (returned from this function) to cancel a timer before it has triggered.

Example:

// Schedule a block to be run after a delay of one second
sched_delay(1, ^{
  NSLog(@"Delayed block triggered");
});

DTimer sched_interval(NSTimeInterval interval, ^([DTimer[, DQueue]]))

Schedule a block in the current queue to be executed every interval seconds. You are responsible for calling DTimerStop(timer) when the timer is no longer needed.

Example:

// Schedule a block to be run every 1.1 seconds
sched_interval(1.1, ^{
  NSLog(@"Perpetual block triggered");
});

DTimer sched_timer(DQueue queue, NSTimeInterval delay, NSTimeInterval interval, ^([DTimer[, DQueue]]))

Schedule a timer on queue which starts after delay seconds and repeats with interval.

If interval has a positive value, the timer repeats every interval seconds. In this case you are responsible for stopping the timer by calling DTimerStop(timer). If interval is zero or negative, the timer is triggered once and then automatically stopped.

Example:

// Start a timer on `fooQueue` after 1.5 seconds, triggering in 3.5 second intervals
sched_timer(fooQueue, 1.5, 3.5, ^(DTimer timer){
  NSLog(@"Timer %@ triggered on foo queue", timer);
});

DTimer DTimerCreate(DQueue queue, NSTimeInterval delay, NSTimeInterval interval, ^([DTimer[, DQueue]]))

Like sched_timer but only creates a timer (does not schedule it). You need to call DTimerResume in order to schedule the timer.

Example:

DTimer timer = DTimerCreate(fooQueue, 1.5, 3.5, ^(DTimer timer){
  NSLog(@"Timer %@ triggered on foo queue", timer);
});
// ...
DTimerResume(timer);

DTimer DTimerResume(DTimer timer)

Schedule a timer that is not yet scheduled (has been paused by DTimerPause or just created by DTimerCreate.)

Each call to DTimerResume must balance a call to DTimerPause, or there will be violent memory violations that will crash all the things. This is a property of libdispatch, trading tolerance of use for efficiency. Note that the timers returned from sched_delay, sched_interval and sched_timer are already resumed.

DTimer DTimerPause(DTimer timer)

Unschedule a timer that has been scheduled. When pausing a timer and later resuming it, the trigger time does not adjust for the time which during the timer was paused.

DTimer DTimerSetInterval(DTimer timer, NSTimeInterval interval)

Modify and reset the interval of a timer.

Calling this function has no effect if the timer source has already been canceled.

Example:

// Execute a block five times with 1 second interval, then change the interval to
// execute the block with 2 seconds interval.
__block int triggerCount = 0;
sched_interval(1.0, ^(DTimer timer){
  NSLog(@"Perpetual block triggered");
  if (++triggerCount == 5) {
    DTimerSetInterval(timer, 2.0);
  }
});

void DTimerStop(DTimer timer)

Cancellation prevents any further invocation of the handler block for the specified timer, but does not interrupt a handler block that is already executing.

MIT License

Copyright (c) 2012 Rasmus Andersson http://rsms.me/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

inter

The Inter font family
Python
16,727
star
2

peertalk

iOS and Mac Cocoa library for communicating over USB
Objective-C
3,363
star
3

fb-mac-messenger

⚑️ Mac app wrapping Facebook's Messenger for desktop
Objective-C
2,860
star
4

kod

Programmers' editor for OS X [DEAD PROJECT]
Objective-C
2,296
star
5

node-imagemagick

Imagemagick module for NodeJS β€” NEW MAINTAINER: @yourdeveloper
JavaScript
1,807
star
6

markdown-wasm

Very fast Markdown parser and HTML generator implemented in WebAssembly, based on md4c
C
1,446
star
7

gotalk

Async peer communication protocol & library
Go
1,193
star
8

estrella

Lightweight and versatile build tool based on the esbuild compiler
TypeScript
1,098
star
9

raster

Raster β€” simple CSS grid system
CSS
806
star
10

js-lru

A fast, simple & universal Least Recently Used (LRU) map for JavaScript
JavaScript
774
star
11

sol

A sunny little virtual machine
C
516
star
12

scrup

Take a screenshot (in OS X) β€” paste the URL somewhere a second later
Objective-C
405
star
13

chromium-tabs

[historical] Chromium tabs for cocoa applications (project no longer maintained)
Objective-C
388
star
14

wasm-util

WebAssembly utilities
TypeScript
353
star
15

figplug

Figma plugin builder
TypeScript
336
star
16

cocui

Cocoa meets WebKit for more rapid UI development
Objective-C
329
star
17

ec2-webapp

A template I use to quickly set up Node.js-backed web apps on Amazon EC2
324
star
18

llvmbox

Self contained, fully static llvm tools & libs
C
317
star
19

move

A simple, functional-biased, prototypal and powerful programming language that runs on any ES3 (or better) JavaScript platform, aimed toward people new to programming
JavaScript
302
star
20

immutable-cpp

Persistent immutable data structures for C++
C++
281
star
21

rsm

Virtual computer
C
267
star
22

compis

Contemporary systems programming language in the spirit of C
C
196
star
23

uilayer

CALayer-style API for building rich, high-performance UI graphics in WebKit
JavaScript
192
star
24

sublime-theme

My Sublime Text theme
Python
187
star
25

scripter

The Scripter Figma plugin
JavaScript
178
star
26

hue

A functional programming language
C++
170
star
27

gitblog

Git-based blog/cms for PHP, meant as a replacement for Wordpress
PHP
164
star
28

co

A programming language in early development
TypeScript
147
star
29

graphviz

Graphviz web app
JavaScript
118
star
30

afcgi

Asynchronous/multiplexing FastCGI for nginx (incl. ref server implementation)
C
101
star
31

rsms-utils

Collection of CLI programs to help with everyday computer life
Shell
99
star
32

colang

Programming language and compiler β€”WORK IN PROGRESSβ€”
C
71
star
33

xsys

A well-defined system API for abstracting the OS platform
C
68
star
34

figma-plugins

Collection of Figma plugins
TypeScript
67
star
35

mkweb

simple static website generator
JavaScript
63
star
36

fontkit

JS & WASM library for working with fonts
C
62
star
37

js-object-merge

3-way JavaScript Object merging -- Object.merge(v1, v1a, v1b) -> v2
JavaScript
54
star
38

smolmsg

Simple messages
Go
54
star
39

tc

Tokyo Cabinet Python bindings β€” In need of a new maintainer
C
54
star
40

js-wasmc

Simplifies building of WebAssembly modules in C/C++ and JS
JavaScript
53
star
41

sigi-pixel-font

Sigi pixel fonts [archived]
52
star
42

WebView-OSX-Screensaver

WebKit web view as a screensaver on OS X
Objective-C
52
star
43

Go.tmbundle

TextMate bundle for the Go programming language
51
star
44

oui

Web-app client-server framework developed as part of dropular.net
JavaScript
49
star
45

wlang

Programming language in development
C
47
star
46

smisk

High performance web service framework, written in C but controlled by Python. Used by Spotify infra 2009–2015.
Python
45
star
47

memex

Software for archiving my digital stuff like tweets
Go
45
star
48

ckit

The little C kit
C
44
star
49

workenv

My personal work environment
Emacs Lisp
44
star
50

dropub

DroPub β€” drop and publish. Simple OS X MenuItem managing secure transfer of files in the background
Objective-C
42
star
51

serve-http

Simple, safe single-file local web server
JavaScript
42
star
52

ghp

Go Hypertext Preprocessor
Go
38
star
53

go-uuid

Binary sortable universally unique identifier
Go
38
star
54

TypoFig

Mac app for assisting type design in Figma
Objective-C
38
star
55

opencv-face-track-basics

Basic code for tracking faces and eyes using OpenCV
C++
37
star
56

qemu-macos-x86-arm64

Run arm64 Linux Alpine virtualized on macOS x86_64 with QEMU
Shell
35
star
57

tspkg

Create small, fast and easily-distributable packages from TypeScript projects
JavaScript
34
star
58

go-immutable

Immutable data structures for Go
Go
34
star
59

webkit-editor

Experimental text editor which runs in the browser
JavaScript
32
star
60

html5-video

Video player in HTML5
JavaScript
30
star
61

jo

Go-style JavaScript ES6 compiler and packager, based on Babel
JavaScript
30
star
62

hovden-stitch

A typeface weekend project from 2002 with a classic "stitching"/"embroidery" look
30
star
63

libcss-osx

Building libcss as Mac OS X universal binary. Developed as part of Kod (rsms/kod)
Objective-C
29
star
64

tumblr-theme-hunch

The theme used on my blog
28
star
65

dawn-lib

Builds Dawn on Linux and macOS as one single easier-to-use library
Shell
28
star
66

browser-require

CommonJS module require() for web browsers
JavaScript
25
star
67

jsont

A minimal and portable JSON tokenizer for building highly effective and strict parsers (in C and C++)
C
25
star
68

prog-lang-tutorial

JavaScript
25
star
69

node-fsdocs

Simple, ACID and versioned file-system based document database
JavaScript
25
star
70

js-fragment

Client-side templating for modern thinkers
JavaScript
24
star
71

node-couchdb-min

Simplistic CouchDB client with a minimal level of abstraction and connection pooling.
JavaScript
24
star
72

fontctrl

Font manager, keeping font files up to date with a distributed repository model
Go
23
star
73

web-clipboard-promise

Demonstrates lazily-evaluated clipboard data on the Web platform
JavaScript
22
star
74

bezier-tangent

BΓ©zier curve toy
JavaScript
22
star
75

twitter-icon

Alternative icon for Twitter.app
21
star
76

dropular-2010

Redacted snapshot of dropular.net, May 2010
JavaScript
21
star
77

dawn-wire-example

[WIP] Demo of a minimal but functional Dawn-based WebGPU client and server
C++
21
star
78

phpab

Abstract Base – universal PHP runtime library
PHP
18
star
79

NodeCocoa

Embed node.js in Cocoa or write whole Cocoa apps in node.js
Objective-C
17
star
80

ortho-remote

Some code for playing with the Teenage Engineering Ortho Remote
Objective-C
16
star
81

ml-kern

Kerning done by machines (a project to learn more about ML)
JavaScript
16
star
82

asl-logging

Convenience functions and example code for using ASL (Apple System Log facility)
C
14
star
83

js-miniglob

Minimal glob JavaScript implementation ported from Go's path/filepath
JavaScript
13
star
84

hunch-cocoa

An assortment of Cocoa β€” mixed extensions and additions to Cocoa
Objective-C
13
star
85

wasm-loader

WebAssembly module loader with import resolution
TypeScript
12
star
86

cmdr

Helps writing command-line programs with subcommands in Go
Go
12
star
87

spotifycocoa

Cocoa framework of libspotify
Objective-C
12
star
88

cgui

super duper simple gui for C, wrapping imgui and stb
C
12
star
89

macfusion

Fork of http://svn.macfusionapp.org/macfusion2/trunk/ β€” With mainly UI changes like menu item icon and OS-standard volume icons) β€” Download latest release build: http://cloud.github.com/downloads/rsms/Macfusion/Macfusion.zip
Objective-C
12
star
90

hunch-upload

Multiple concurrent files uploads with progress in pure HTML
JavaScript
11
star
91

functional.js

Work in a functional style with JavaScript and TypeScript
JavaScript
11
star
92

coxlang

Programming language w/ subproject that implements the Go scheduler in C++
C++
11
star
93

lolcatos

The lolcat operating system
Assembly
11
star
94

cometps

Simple comet pub/sub
C
9
star
95

node-imgdb

Image fingerprinting
C++
8
star
96

ssl-client-auth-demo

Demonstrates "client-authenticated TLS handshake"
Shell
8
star
97

connect_facebook

Facebook session support for Connect
8
star
98

mode

Node module manager and repository
JavaScript
8
star
99

flup

Drag-and-drop to quickly put images on Flickr
Objective-C
8
star
100

ipvec

Educational persistent vector implementation in C
C
8
star