With the actual implementation of TMultiReadExclusiveWriteSynchronizer, you must do in the same Thread MyMultiReadExclusiveWriteSynchronizer.beginRead and MyMultiReadExclusiveWriteSynchronizer.endRead
However me I need to call MyMultiReadExclusiveWriteSynchronizer.beginRead in one thread and call MyMultiReadExclusiveWriteSynchronizer.endRead in another thread (this because I use winapi IO completion block)
Is there any way ?
Related
For the purposes of this question, assume that I need to run some function on some object and that function will take a long time to execute (minutes). Also assume that I have no control over this function (*). How do I now cancel this function's execution?
I want to run it in a background thread to keep the main thread free and I could do that with GCD, NSOperation or NSThread. However, as far as I know, none of these support forced stopping. They can all be cancelled, but this cancellation must be implemented in the function itself - but I don't have access to that function, so I can't do that. The closest I got was using NSThread and exit(), but unfortunately it can't be applied to a instance variable (see the code example). My current plan is to try to send a notification and observe that within the object/function and kill the thread from within using Thread.exit(). I'm justing wondering if there is a "cleaner" or easier way, either built-in or 3rd party.
let someObject = Object()
// Using GCD
dispatchQueue.async { someObject.expensiveFunction() }
// Using NSOperation
operationQueue.addOperation { someObject.expensiveFunction() }
// Using NSThread
let thread = Thread { someObject.expensiveFunction() }
thread.exit() // exit is not available on an instance
(*) In this case I do have control over the function and could implement an actual cancellation, but due to the libraries I'm using, this would require a lot of refactoring.
I want to know As we all know how asynchronous task are necessary for concurrency but Wanted to know why we need the synchronous tasks. while we can achieve the same with the normal usage of function.
Thanks & regards
Rohit
When you calls something synchronously, it means that 'the thread that initiated that operation will wait for the task to finish before
continuing'. Asynchronous means that it will not wait for finish the task.
synchronous calls stops your current action and returns when the call returned. with asynchronous calls you can continue.
synchronous is the opposite of asynchronous code, and therefore is ordinary code.
At the end, if asynchronous is totally out of scope then you will not emphasize the word synchronous.
It helps to synchronise threads, as the name suggests.
consider a typical usage of GCD async and sync (pseudo)
async background_thread {
//1 call webservice or other long task that would block the main thread
sync main_thread {
//2 update UI with results from 1
}
//3 do something else that relies on 2
}
now if 2 was in an async and you needed to do something at 3 that relies on the updates at 2 to have happened, then you are not guaranteed (and most likely wont) get the behaviour you are expecting. instead, you use a sync to make sure that the task is completed before continuing the execution in the background thread.
If you are asking now, why not just take out the sync/async around 2 so it executes in order anyway? the problem is, the UI must not be updated on a background thread otherwise the behaviour is undefined (which usually means the UI lags a lot). So in essence what happens is the background thread waits at 2's sync until the main thread gets round to executing that block, then it will continue with the rest of the execution on the background thread.
If you were dealing with a task that doesnt require the main thread (or some other thread) to execute properly, then yes you may as well take out the sync at 2.
This is just one example of how a sync is useful, there are others if you are doing advanced threading in your app.
Hope this helps
Typically it's because you want to do an operation on a specific different thread but you need the result of that operation. You cannot do the operation asynchronously because your code will proceed before the operation on the other thread completes.
Apple has a very nice example:
func asset() -> AVAsset? {
var theAsset : AVAsset!
self.assetQueue.sync {
theAsset = self.getAssetInternal().copy() as! AVAsset
}
return theAsset
}
Any thread might call the asset method; but to avoid problems with shared data, we require that only functions that are executed from a particular queue (self.assetQueue) may touch an AVAsset, so when we call getAssetInternal we do it on self.assetQueue. But we also need the result returned by our call to getAssetInternal; hence the call to sync rather than async.
I have this piece of code:
[[FBController sharedController] getUserDetailsWithCompletionBlock:^(NSDictionary *details)
{
// Updating UI elements
}];
I don't understand a thing: when the block is fired, the secondary thread is still running. Isn't it more correct that the completion of a block should be executed on main thread automatically?
I know that I am wrong with something and I need a couple of explanations.
The Facebook SDK documentation should give you more details, but in general a well-behaved SDK would call completion blocks on the same thread that the SDK was called from. Any long-running or asynchronous operations that the SDK may perform should operate on a separate thread, usually only visible to the SDK. Whether or not that separate thread is still running or not, is an implementation detail of the SDK - and you shouldn't care about it from the client code perspective.
You can visualise it like this:
Client Code (Main Thread) : [Request]--[Response]-[Continue Thread]-------[Completion Block]
v ^ ^
SDK Code (Main Thread) : [Immediate Operations] |
v |
SDK Code (Private Thread) : [Long Running / Asynchronous Operations]----[Finished]
In the specific example you posted, there's no 'Response' from the getUserDetailsWithCompletionBlock method, so the thread carries on as usual.
The missing piece to the jigsaw puzzle might be - "How does my completion block get executed on the main thread". Essentially this comes down to the Runloop system. Your main thread isn't actually owned and operated by your code, it's behind the scenes. There's a Main Runloop which periodically looks for things to do. When there's something to do, it operates those somethings on the main thread sequentially. When those somethings have finished, it goes back to looking for something else to do. The SDK basically adds your completion block to the main runloop, so the next time it fires, your block is there waiting to be executed.
Other things that the runloop might be doing are:
UI Updates
Delegate callbacks from UI code
Handling Timers
Touch Handling
etc... etc...
I'm in trouble understanding the real difference between IDSYNC and IDNOTIFY, what means synchronous / asynchronous
in respect to the lines of code I write ?
procedure TForm1.IdTCPServerExecute(AContext: TIdContext);
begin
....
DoSomeThing (TIDNotify) ....
DoSomethingOther(TIDsync) ......
end;
Why can't I be sure that both lines of code are executed within the TCPServer Execute function?
Is there only the risk that a few lines of code are not executed within my TIDSynfunction or how can a Deadloack be explained ?
TIdSync and TIdNotify accomplish the same goal - to execute a piece of code in the context of the main thread - but they do it in different ways.
TIdSync is synchronous. The TIdSync.Synchronize() method blocks the calling thread until after the main thread has called the TIdSync.DoSynchronize() method and it has exited. A deadlock can occur if TIdSync.Synchronize() is called within a server event handler while the main thread is shutting down that server. This is because the main thread is blocked waiting for the server to terminate its threads. But the thread is blocked waiting for the main thread to process the sync request.
TIdNotify is asynchronous. The TIdNotify.Notify() method adds the TIdNotify.DoNotify() method into a background queue and exits immediately, so the calling thread is not blocked. The main thread calls the TIdNotify.DoNotify() method at its leisure. There is no deadlock in this situation.
How does a thread knows when to exit?
SITUATION:
-while the main program must wait for the threads to run to completion.
-This can be done by using a prototype function called pthread_join.
-after all, a call to this function waits for the termination of the thread whose id is given by thread itself.
After you have called pthread_join(ptherad_t &var)the main will wait untill all the threads for which you have called join have exited.
once all the threads are completed their tasks,
when it calls pthread_exit(NULL) main will exit.
inside the thread after its task is completed you need to call pthread_exit(NULL) which will stop the excution of the thread.But this is not mandatory and the thread can simply return which means that the thread has completed.
when it(thread) calls pthread_exit(NULL),the calling thread will exit.