How to write to an array from a dispatch_apply (GCD) loop?

I wrote code to compute the dynamics of a large set of coupled basic equations using the Runge-Kutta method. The code contains many for-loops where each step is independent. I intend to use Grand Central Dispatch to speed up the program. I based my attempt on an example that I found at http://www.macresearch.org/cocoa-scientists-xxxi-all-aboard-grand-central . Neither my code nor the macro network example compiles on my computer (MacOSX 10.6.8 Xcode 4.0.2). So here is my code:

... double values[SpaceSize], k1[SpaceSize]; for ( int t=1 ; t<Time ; t++ ) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //k1 for (int k=0 ; k<SpaceSize ; k++ ) values[k]=Concentration[k][t-1]; dispatch_apply(SpaceSize, queue, ^(size_t k) { k1[k]=h * derives(values, SpaceSize, k); //<--error } ); ... 

It fails with an error:

Semantic problem: cannot refer to declaration with modified change type inside block

I tried replacing arrays (values, k1) with vectors, but instead I get another error message:

Semantic issue: read-only variable not assigned

That's where I got stuck, not knowing what these error messages are trying to tell me. I spend quite a lot of time and ask if anyone can help. I would be very grateful for the advice or the best ways to solve this problem.

+6
source share
2 answers

error: cannot refer to declaration with array type inside block

As part of the implementation of blocks, access to the C array from blocks is not allowed. (I cannot find documentation about this ...)

There is an easy fix :-)

 double valuesArray[SpaceSize], k1Array[SpaceSize]; double *values = valuesArray, *k1 = k1Array; 
+14
source

To save to a captured variable, you need to add the __block repository __block to your declaration. This should solve the std::vector problem you see.

A problem with the changed type changes the sound type as if you were using an array of variable length. They cannot be mentioned from inside the blocks, because they cannot be reliably copied into the block context (basically, the user-defined type C struct ), and they can ruin offsetof style calculations when working with the context. You can solve this problem by working with a fixed-size variable (just use the maximum size you need) by moving the arrays to global / static storage or by highlighting the pointer and doing pointer arithmetic to access the second dimension yourself.

+1
source

Source: https://habr.com/ru/post/892174/


All Articles