Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c++ - How to write into an array from a dispatch_apply (GCD) loop?

I have written code to calculate the dynamics of a large set of coupled master equation using the Runge-Kutta-method. The code contains a lot of 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 I found at http://www.macresearch.org/cocoa-scientists-xxxi-all-aboard-grand-central . Neither my code nor the example on macresearch compile on my machine (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 breaks with the error:

Semantic Issue: Cannot refer to declaration with a variably modified type inside block

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

Semantic Issue: Read-only variable is not assignable

That is where I'm stuck, not really knowing what those error messages are trying to tell me. I spend quite some time searching and asking around if anyone could help. I would be very grateful for tips or better ways to solve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

error: cannot refer to declaration with an array type inside block

Under the blocks implementation, it is not allowed to access to an C array from blocks. (I can't find the documentation about it...)

There is an easy fix :-)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...