Ameba::Rule::Lint::SharedVarInFiber
Inherits Ameba::AST::Util < YAML::Serializable < Ameba::Rule::Base < Ameba::Config::RuleConfig < Reference < Object
A rule that disallows using shared variables in fibers, which are mutated during iterations.
In most cases it leads to unexpected behaviour and is undesired.
For example, having this example:
n = 0
channel = Channel(Int32).new
while n < 3
n = n + 1
spawn { channel.send n }
end
3.times { puts channel.receive } # => # 3, 3, 3
The problem is there is only one variable n shared between fibers
and when channel.receive is executed its value is 3.
To solve this, the code above needs to be rewritten to the following:
n = 0
channel = Channel(Int32).new
while n < 3
n = n + 1
m = n
spawn { channel.send m }
end
3.times { puts channel.receive } # => # 1, 2, 3
This rule is able to find the shared variables between fibers, which are mutated during iterations. So it reports the issue on the first sample and passes on the second one.
There are also other techniques to solve the problem above which are officially documented
YAML configuration example:
Lint/SharedVarInFiber:
Enabled: true
Constants
Constructors
A rule that disallows using shared variables in fibers, which are mutated during iterations.
In most cases it leads to unexpected behaviour and is undesired.
For example, having this example:
n = 0
channel = Channel(Int32).new
while n < 3
n = n + 1
spawn { channel.send n }
end
3.times { puts channel.receive } # => # 3, 3, 3
The problem is there is only one variable n shared between fibers
and when channel.receive is executed its value is 3.
To solve this, the code above needs to be rewritten to the following:
n = 0
channel = Channel(Int32).new
while n < 3
n = n + 1
m = n
spawn { channel.send m }
end
3.times { puts channel.receive } # => # 1, 2, 3
This rule is able to find the shared variables between fibers, which are mutated during iterations. So it reports the issue on the first sample and passes on the second one.
There are also other techniques to solve the problem above which are officially documented
YAML configuration example:
Lint/SharedVarInFiber:
Enabled: true
Class methods
Returns true if this rule is deprecated, false otherwise.
Returns the deprecation reason for this rule, if there is any.
Returns the documentation URL for this rule.
Ameba::Rule::Lint::Syntax.documentation_url
# => "https://crystal-ameba.org/api/master/Ameba/Rule/Lint/Syntax.html"
Returns the documentation for this rule, if there is any.
module Ameba
# This is a test rule.
# Does nothing.
class Rule::MyRule < Rule::Base
def test(source)
end
end
end
Ameba::Rule::MyRule.parsed_doc # => "This is a test rule.\nDoes nothing."