Skip to content

Commit

Permalink
feat: initial
Browse files Browse the repository at this point in the history
  • Loading branch information
GeopJr committed Jan 29, 2022
0 parents commit 52fc377
Show file tree
Hide file tree
Showing 10 changed files with 382 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*.cr]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI
on:
push:
pull_request:
branches: [master]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Download source
uses: actions/checkout@v2
- name: Install Crystal
uses: crystal-lang/install-crystal@v1
- name: Install shards
run: shards install
- name: Run tests
run: crystal spec --order=random -Dpreview_mt
- name: Build docs
run: crystal docs
- name: Push to pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs
- name: Check formatting
run: crystal tool format; git diff --exit-code
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf

# Libraries don't need dependency lock
# Dependencies will be locked in applications that use them
/shard.lock
132 changes: 132 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[email protected].
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][mozilla coc].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][faq]. Translations are available
at [https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[mozilla coc]: https://github.com/mozilla/diversity
[faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
25 changes: 25 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
BSD 2-Clause License

Copyright (c) 2022, Evangelos "GeopJr" Paterakis
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<h1 align="center">non-blocking-spawn</h1>
<h4 align="center">A Crystal shard that spawns a fiber in any worker thread BUT the current one.</h4>

## Purpose

When running Crystal with [`-Dpreview_mt`](https://crystal-lang.org/2019/09/06/parallelism-in-crystal.html) sometimes fibers spawn in the current thread that might be blocked at that moment or for the duration of the run.
This happens by design. Top level `spawn` has an option to force a fiber to spawn in the current thread (`same_thread`), but not one for the opposite (since it's probably not in high demand).
That's what this shard adds.

It's a copy of the spawn method but when `same_thread` is false, it goes through all available worker threads, filters out the current one and picks one at random to spawn the fiber in.

While it might sound a bit useless, there are legit use cases:

- GTK: The main thread is blocked and remains blocked for the whole time. Using non-blocking-spawn you can spawn fibers and be sure that all of them will execute and finish.
- Wider range of examples (see: [`./spec/non-blocking-spawn_spec.cr`](./spec/non-blocking-spawn_spec.cr)): In the spec, two of the tests are similar but one of them uses non-blocking-spawn while the other uses top level spawn. The first one finishes with `i` being equal to `4` (/default amount of worker threads) while the second one finishes with `i` being equal to `3`. This is due to one of the fibers being spawned in the current thread.

## WARNING

- PLEASE don't use with newer or older versions of Crystal without checking that the spawn method is the same as the top level one (apart from the non-blocking-thread part). This shard uses private interfaces that may break at any point without notice.

- Assumes that all crystal commands (including `spec`) are being ran with the `-Dpreview_mt` flag. The `Non::Blocking.threads` method is available to check whether there are worker threads - other than the current one - and act accordingly (probably run in sync).

## Installation

1. Add the dependency to your `shard.yml`:

```yaml
dependencies:
non-blocking-spawn:
github: GeopJr/non-blocking-spawn
```

2. Run `shards install`

## Usage

You can find non-blocking-spawn's docs on the sidebar.

```crystal
require "non-blocking-spawn"
Non::Blocking.spawn do
# expensive blocking code
end
# other expensive blocking code
```

## Development

- Everything runs with the `-Dpreview_mt` flag.
- When bumping Crystal version make sure that the method matches the top level one.

## Contributing

1. Read the [Code of Conduct](https://github.com/GeopJr/non-blocking-spawn/blob/main/CODE_OF_CONDUCT.md)
2. Fork it (<https://github.com/GeopJr/non-blocking-spawn/fork>)
3. Create your feature branch (`git checkout -b my-new-feature`)
4. Commit your changes (`git commit -am 'Add some feature'`)
5. Push to the branch (`git push origin my-new-feature`)
6. Create a new Pull Request
9 changes: 9 additions & 0 deletions shard.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: non-blocking-spawn
version: 1.0.0

authors:
- Evangelos Paterakis <[email protected]>

crystal: ~>1.3.2

license: MIT
57 changes: 57 additions & 0 deletions spec/non-blocking-spawn_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
require "./spec_helper"

describe Non::Blocking do
it "has more than one worker threads" do
Non::Blocking.threads.size.should be > 1
end

# Spawns Non::Blocking.threads.size + 1 fibers in any worker thread
# BUT the current one. Each fiber increases i by one.
# Then does a blocking infinite loop checking whether all fibers finished or 10 seconds passed.
# The test passes if i equals Non::Blocking.threads.size + 1
it "spawns fibers in any thread but the current one" do
i = 0
finish = 0
threads_plus_one = Non::Blocking.threads.size + 1
threads_plus_one.times do
Non::Blocking.spawn do
i = i + 1
end
end

safe_stop = Time.utc.to_unix_ms
loop do
if i == threads_plus_one || Time.utc.to_unix_ms - safe_stop > 10000
# Set finish just in case for whatever reason a fiber finishes afterwards.
finish = i
break
end
end
finish.should eq(threads_plus_one)
end

# Spawns Non::Blocking.threads.size + 1 fibers in any worker thread
# INCLUDING the current one. Each fiber increases i by one.
# Then does a blocking infinite loop checking whether all fibers finished or 10 seconds passed.
# The test passes if i equals Non::Blocking.threads.size. (One less that the previous test).
# This test proves that one fiber spawned in the current thread that was blocked.
it "spawns fibers in any thread including the current one" do
i = 0
finish = 0
threads_plus_one = Non::Blocking.threads.size + 1
threads_plus_one.times do
spawn do
i = i + 1
end
end

safe_stop = Time.utc.to_unix_ms
loop do
if i == threads_plus_one - 1 || Time.utc.to_unix_ms - safe_stop > 10000
finish = i
break
end
end
finish.should eq(threads_plus_one - 1)
end
end
2 changes: 2 additions & 0 deletions spec/spec_helper.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require "spec"
require "../src/non-blocking-spawn"
52 changes: 52 additions & 0 deletions src/non-blocking-spawn.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# This is a fork of top level spawn,
# but when same_thread is false, it makes sure
# that the fiber spawns in any worker thread BUT the current one.
#
# If only the current one is available, it falls back to leaving it up to
# Crystal::Scheduler to decide.
#
# https://crystal-lang.org/api/1.3.2/toplevel.html#spawn%28%2A%2Cname%3AString%3F%3Dnil%2Csame_thread%3Dfalse%2C%26block%29-class-method
#
# https://github.com/crystal-lang/crystal/blob/932f193ae/src/concurrent.cr#L60-L67
module Non::Blocking
extend self

# Spawns a fiber in either the same worker thread or any BUT the current one.
#
# Example:
# ```
# Non::Blocking.spawn do
# loop do
# puts "hello world"
# end
# end
# ```
def spawn(*, name : String? = nil, same_thread = false, &block) : Fiber
fiber = Fiber.new(name, &block)
if same_thread
fiber.@current_thread.set(Thread.current)
else
non_blocking_threads = threads
# If there are threads available other than the current one,
# set fiber's thread as a random one from the array.
fiber.@current_thread.set(non_blocking_threads.sample) unless non_blocking_threads.size == 0
end
Crystal::Scheduler.enqueue fiber
fiber
end

# Returns the amount of available worker threads excluding the current one.
#
# Example:
# ```
# puts Non::Blocking.threads.size
# ```
def threads : Array(Thread)
threads = [] of Thread
Thread.unsafe_each do |thread|
next if thread == Thread.current
threads << thread
end
threads
end
end

0 comments on commit 52fc377

Please sign in to comment.