multithreading - Array Offset C++ pthreads return -
i running following code in c++.
it runs expected, however, first result null in second loop...however, every ensuing result correct.
pthread_t pthread_t_array[thread_count]; int ireturn[thread_count]; float chunk_elements[thread_count]; (int = 0; < thread_count; i++) { float vector_chunk[3] = {2.0,4.0,3.0}; pthread_t x; pthread_t_array[i] = x; ireturn[i] = pthread_create(&x,null,worker,(void *) vector_chunk); } (int = 0; < thread_count; i++) { void * result; ireturn[i] = pthread_join(pthread_t_array[i],&result); // lines below: @ = 0, result = null // however, @ every other value of i, 14 returned expected. if (result != null){ chunk_elements[i] = *(float *) result; } free(result); }
the full code here.
i not sure why there array offset (at line testing if result null--at = 0, result null, every other i, not). seems going correctly.
correction: not offset, rather, first value null, there 1 less value.
if, seems likely, worker()
thread, code not shown, attempts read vector_chunk
parameter thread receives, undefined behavior, , bug.
this because vector_chunk
array has automatic scope, , exists until end of for-loop iteration. pthread_create()
returns, , return value gets put array, loop iteration ends, , vector_chunk
array goes out of scope, , destroyed.
there no guarantee thread execute , read vector_chunk
before parent thread reaches end of loop iteration, when vector_chunk
goes out of scope. subsequent vector_chunk
going out of scope, attempt worker()
access vector_chunk
parameter undefined behavior, , bug.
the solution dynamically allocate parameter thread, initialize, , start thread, passing dynamically-allocated parameter, thread parameter data. thread responsible retrieving parameter data, , deallocated parameter.
Comments
Post a Comment