Reputation: 1151
Consider the following code:
typedef double (*fpointer)(void*);
typedef struct {
int data1;
double data2;
} data_t;
double stuff(void* arg) {
data_t *d = (data_t *)arg;
...
// Do random things
...
return data2;
}
And consider I have a non-blocking function:
void func(fpointer f, data_t* d)
Which essentially runs f(d)
but returns immediately without waiting for the f(d)
to complete (similar to something like MPI_Isend/MPI_Irecv).
Now I want to run func
hundreds of times, but with different data. Is something like the code below safe to run without inhibiting a race-condition? If it does exhibit undefined behaviour, what would be an alternative to achieving such a task without creating hundreds of data structures?
data_t d;
d.data1 = 1;
d.data2 = 1.5;
for (int i = 0; i < 1000; i++) {
d.data2 += 1.0;
func(stuff, &d);
}
If you need more clarification, please let me know. I appreciate any help.
Upvotes: 0
Views: 113
Reputation: 8463
Not safe at all - if, as you imply - there is processing going on in the background. You're re-using the same instance of d
for each iteration; d
is being passed by reference.
Consider making a new copy of d
, or using pass-by-copy into func
. Since data_t
is relatively small, you won't take much of a hit doing that in this case.
If you can't copy through the parameter, perhaps func
can copy internally (introduces semantics on func
you might not want) or your caller can pass in distinct instances.
Upvotes: 1