How execution of a coroutine resume in main function? - multithreading

If we use coroutine in main function then, how execution of coroutine resume after delay.
Like in this image, coroutine is in main function and after delay of 2 second code resumes. So I just wanted to know how execution going back to the code after delay. I know about state machine and how coroutine works in android. I am asking about kotlin with main function( Not in android activity ).

If you know how coroutines work in Android I am unsure what is confusing you. Coroutines are non blocking so as soon delay is done print will get executed.
Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.

GlobalScope.launch {
delay(2000)
print("World)
}
println("Hello")
Thread.sleep(3000)
Without going much into the detail of coroutine suspend/resume execution using continuation or state-machine
how execution of coroutine resume after delay
Because, you are blocking the main thread. Thread.sleep(3000) blocks the main thread for 3secs. If you remove Thread.sleep you can see the difference.
In android it's isn't required, reason being android UI thread runs on Handler/Looper concept, which is same as any other thread, only difference being, it always keep the Main/UI thread alive and keep executing the tasks from the message-queue.

Related

Does Scala Future[T] block internally? What happens inside Scala Future?

val future = Future {
println("hello")
Thread.sleep(2000)
}
future.onComplete(_ => println("done"))
The code in the future above blocks.
My question is: since Future uses an ExecutionContext. Does it mean that some thread in this thread pool will be blocked by this future while executing the code inside it?
What thread exactly will call the callback? Another thread from the thread pool? How will it find out that the code executed inside this future is finished?
Assuming you're calling code that blocks in a Future:
since Future uses ExecutionContext. Does it mean, that some thread in this thread pool will be blocked by this future while executing the code inside it?
Essentially, yes. If you're calling blocking code, something has to be blocked. An ExecutionContext is more general than a thread pool, though. It can be thread pool, but it can also be just something that manages calls in some other way. Still, something will be blocked, more often than not it will be a thread. scala.concurrent.ExecutionContext.Implicits.global is a ForkJoinPool, for example.
What thread exactly will call the callback?
That is mostly up to the ExecutionContext to decide. You can print Thread.currentThread in your callback code, but there is no reason (other than maybe debugging) why you really need to know this information. Your code certainly shouldn't need to know. Typically this means the next available thread in the pool, which could be the same thread that executed the body of the Future, or a different one. It appears that the same thread that executes the original Future will dispatch the callbacks, but that only schedules them for execution.
How will it find out, that the code execution inside this future is finished?
Calling onComplete will either execute immediately if the underlying Promise of the Future is in the completed state, or a CallbackRunnable will be added to a list of listeners to be executed when the promise is completed. DefaultPromise#tryComplete will call the listeners immediately after the computation has executed. See this excerpt of the current code.

Mechanism of join() in multithreading

I was studying about multi-threading and came across join().
As I understand right, using join() on the thread makes process wait until 'joined' thread terminates. For example, calling t1.join() in main will make main wait until the job in thread t1 is finished and t1 terminates.
I'm just curious that how the function join() make this possible - how does it make current thread 'blocked' inside the function? Does join() force execution of joined thread first so any other thread should wait until that thread terminates? Or, is there some way to communicate between two threads(the thread who called join() and the thread who is joined)?
I will be waiting for the answer. Thanks a lot!
To be able to join you need to be able to wait on some event. Then join looks like this:
function join(t : Thread)
// do this atomically
if already done
return
wait on termination event of t
end
Waiting can be done in one of two ways:
Looping and periodically checking if the event has happened (busy wait)
Letting the system reclaim the resources of the thread and be woken up on a system event, in that case waking the thread is managed by the scheduler of the OS
It's rather language specific.
Once you create a thread, it starts running.
A join operation is when your main process stops and waits for the thread to exit and capture a return code. It will block until your thread completes - that's rather the point, as it allows for a synchronization to occur - everything in your program is at a 'known state'.
Related is the detach operation, which is effectively saying 'I don't care any more'.

set a deadline for each callback in an event-driven/ event-loop based program

In a typical ASIO or event-based programming library like libevent, is there a way to set a deadline for each callback?
I am worried about possible infinite loops within the callbacks. Is there a way to gracefully detect them, remove the misbehaving callback from task queue and continue processing other tasks in the queue?
I can think of a way to detect it through an external thread and kill the event-loop thread and create a different thread but I am trying to see if there are any other commonly used methods. I believe this is a problem which someone has faced at some point of time and thought through a solution
There is no general way to unstick a thread without its cooperation, whether it's running a callback or not. The thread may hold critical locks or may have acquired resources that would never get released if the thread was somehow coerced to stop from the outside.
If you really do need this functionality, then all code that could potentially be interrupted must be designed to support some specific method of interruption. You can start a deadline timer when you enter the callback and cancel it when you're finished. The deadline timer would have to trigger the thread's interruption mechanism. You'd need at least one other thread running the I/O service in order for some thread to run the timer handler while the callback was running in another thread.
You can also isolate the code in its own process with some kind of wrapper. Then if the code fails to terminate, you can kill the process from the outside.

Can i wake a specific Haskell thread?

Is there a way to wake a specific thread in Haskell? There is a function that suspends the current thread. But the waking counterpart doesn't seem to exist.
yield doesn't suspend the current thread - it moves it to the back of the run queue. It's still in the run queue, it just makes sure that other runnable threads (potentially not all runnable threads, if there are multiple execution contexts defined, which makes this a a pretty weak guarantee) have a chance to run before it continues. For the most part, you should ignore yield. The exception is when you understand exactly what it does, and why that matters.
To actually suspend and resume a thread, MVars are the way to go. When a thread waits on an empty MVar, it is removed from the runnable queue. When a value is put into an MVar, a thread waiting on it (I believe in GHC it's always the thread that has been waiting on that MVar longest, but it's not guaranteed) is put back into the runnable queue.

Tell if 'elapsed' event thread is still running?

Given a System.Timers.Timer, is there a way from the main thread to tell if the worker thread running the elapsed event code is still running?
In other words, how can one make sure the code running in the worker thread is not currently running before stopping the timer or the main app/service thread the timer is running in?
Is this a matter of ditching Timer for threading timer using state, or is it just time to use threads directly?
Look up ManualResetEvent, as it is made to do specifically what you're asking for.
Your threads create a new reset event, and add it to an accessible queue that your main thread can use to see if any threads are still running.
// main thread owns this
private List<ManualResetEvent> _resetEvents;
...
// main thread does this to wait for executing threads to finish
WaitHandle.WaitAll(_resetEvents.ToArray(), 2000, false)
...
// worker threads do this to signal the thread is done
myResetEvent.Set();
I can give you more sample code if you want, but I basically just copied it from the couple articles I read when I had to do this a year ago or so.
Forgot to mention, you can't add this functionality to the default threads you'll get when your timer fires. So you should make your timer handler be very lean and do nothing more than prepare and start a new worker thread.
...
ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorkerDelegate),
myCustomObjectThatContainsAResetEvent);
For the out of the box solution, there is no way. The main reason is the thread running the TimerCallback function is in all likelihood still alive even if the code running the callback has completed. The TimerCallback is executed by a Thread out of the ThreadPool. When the task is completed the thread does not die, but instead goes back into the queue for the next thread pool task.
In order to get this to work your going to have to use a manner of thread safe signalling to detect the operation has completed.
Timer Documentation

Resources