ios - Is a __block variable assignment thread-safe to read immediately after the block? -


__block nshttpurlresponse *httpresponse;  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); nsurlsessiondatatask *task = [session datataskwithrequest:request completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) {     if (!error)          httpresponse = (nshttpurlresponse *)response;     }      dispatch_semaphore_signal(semaphore); }]; [task resume]; dispatch_semaphore_wait(semaphore, dispatch_time_forever); 

is safe read httpresponse after this? semaphore waits block compete execution. if there no error, assignment seen or have synchronise or create memory barrier outside block?

does waiting on semaphore implicitly perform synchronisation makes __block variable safe read immediately. if done thread.join() in java instead of semaphore, safe since guarantees happens-before relationship assignment in "block".

the short answer yes.

the semaphore lock forces thread operating stop execution until receives enough unlock signals proceed.

the variable have defined modified on other thread before semaphore allowed continue executing, assignment should have safely occurred.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -