Skip to content

Cooperative multitasking system written is Swift. Comes with event loop

License

Notifications You must be signed in to change notification settings

swiftstack/fiber

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

88 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fiber

Cooperative multitasking written in swift with only one exception.

Package.swift

.package(url: "https://github.com/swiftstack/fiber.git", .branch("fiber"))

Usage

You can find this code and more in examples.

Real World Example (using Network)

As you can see, no callback hell:

import Network

async {
    let service = client.connect("http://election.online")
    service.login(using: cookies)
    guard service.vote(for: "Thor") == .success else {
        fatalError("we're doomed")
    }
    service.syscall(.coverMyTracks)
    service.logout()
}

loop.run()

Transfer execution

fiber {
    print("hello from fiber 1")
    fiber {
        print("hello from fiber 2")
        yield()
        print("bye from fiber 2")
    }
    print("no, you first")
    yield()
    print("bye from fiber 1")
}

FiberLoop.main.run()

// hello from fiber 1
// hello from fiber 2
// no, you first
// bye from fiber 2
// bye from fiber 1

Channel

var channel = Channel<Int>()

fiber {
    while let value = channel.read() {
        print("read: \(value)")
    }
    print("read: the channel is closed.")
}

fiber {
    for i in 0..<5 {
        channel.write(i)
    }
    channel.close()
}
// read: 0
// read: 1
// read: 2
// read: 3
// read: 4
// read: the channel is closed.

Timer

import Time

fiber {
    fiber {
        sleep(until: .now + 2.ms)
        print("fiber 2 woke up")
    }
    sleep(until: .now + 1.ms)
    print("fiber 1 woke up")
}

FiberLoop.main.run(until: .now + 5.ms)

// fiber 1 woke up
// fiber 2 woke up

Releases

No releases published

Packages

No packages published