# Using FLoops.jl to update array counters

**URL:** https://discourse.julialang.org/t/using-floops-jl-to-update-array-counters/58805
**Category:** General Usage
**Tags:** parallel
**Created:** [April 8, 2021, 7:28am UTC](https://discourse.julialang.org/t/using-floops-jl-to-update-array-counters/58805 "2021-04-08T07:28:49Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![tkf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkf/32/17635_2.png) [@tkf](https://discourse.julialang.org/u/tkf)
#### Post date: [April 8, 2021, 8:58am UTC](https://discourse.julialang.org/t/using-floops-jl-to-update-array-counters/58805/2 "2021-04-08T08:58:47Z")

</div>

`counter_odds[ind] += ...` is the problematic part (though the error message can be improved). In particular, you can’t use shared mutable state like this in parallel programming as it’d invoke a data race. Here is one way to do it

```julia
function parallel_test(Input, N_rows)
    counter_evens = 0

    @floop for i = 1:N_rows
        a = round(Input[i,1])

        if a%2 == 0
            c_evens = 1
            @reduce(counter_evens += c_evens)
        else
            c_odds= 1
            ind = min(max(round(Int, rand()*a), 1), N_rows) # get an integer
            another = ind => c_odds
            @reduce() do (counter_odds = zeros(Int16, (N_rows)); another)
                if another isa Pair
                    counter_odds[first(another)] += last(another)
                else
                    counter_odds .+= another
                end
            end
        end
    end

    return counter_evens, counter_odds
end

```

`another isa Pair` is a bit ugly “hack.” If you have a (hypothetical) `OneHotVector`, you can also write it as

```julia
another = OneHotVector(ind => c_odds) # s.t. another[ind] == c_odds and 0 elsewhere
@reduce() do (counter_odds = zeros(Int16, (N_rows)); another)
    counter_odds .+= another
end

```

which clarifies the symmetry of this reduction. See also the histogram section in [A quick introduction to data parallelism in Julia](https://juliafolds.github.io/data-parallelism/tutorials/quick-introduction/#practical_example_histogram_of_stopping_time_of_collatz_function) for a similar example. (I’m also writing another tutorial specifically for reduction with mutable states but it’s not finished yet.)

---

_[View the full topic](https://discourse.julialang.org/t/using-floops-jl-to-update-array-counters/58805)._
