What's the principle of blocking mode? - c++

Like blocks until the file is done playing, what's the principle and how to implement this?

"blocking" means that the operation will not return control to its caller until whatever it's "blocking until" is true.
This can be implemented in several ways:
Delegate the responsibility for blocking to someone else. For example, call pthread_mutex_lock, which may block. This makes your function block too. Other functions doing this are read and any other system call which says it may block.
Spin. In other words, have some code that looks like while (!condition) {}. This will eat an entire CPU core, so it's not a good practice if you're going to be blocking for any significant amount of time.
Use a signal handler. Call sleep(5000) or some such, and terminate the sleep via SIGALARM or another asynchronous method.
In the case of a media player, "blocking until the file is done playing" just means "waits until the media file is done playing before returning".

let a thread wait for an event which will be fired by another thread when file is done playing.

Related

Libcurl - curl_multi_wakeup

Reading the function description curl_multi_wakeup: enter link description here
Calling this function only guarantees to wake up the current (or the
next if there is no current) curl_multi_poll call, which means it is
possible that multiple calls to this function will wake up the same
waiting operation.
I am confused by the phrase - "the same waiting operation". How's that?
That is, suppose I have a function curl_multi_poll() in event standby mode in thread "A".
Now, for example, I call the curl_multi_wakeup() function twice from thread "B" and thread "C".
And what happens judging by this phrase:
...function will wake up the same waiting operation.
It turns out that the function curl_multi_poll - wakes up only once ?
curl_multi_wakeup is meant to be used with a pool of threads waiting on curl_multi_poll.
What the document says is that if you call curl_multi_wakeup repeatedly, it will possibly wake up only a single thread, not necessarily one thread for each call to curl_multi_wakeup.
curl_multi_poll() is a relatively new call, designed to simplify "interrupting" threads waiting on curl_multi_poll(). Here's a good explanation:
https://daniel.haxx.se/blog/2019/12/09/this-is-your-wake-up-curl/
curl_multi_poll()
[is a] function which asks libcurl to wait for activity on any of the
involved transfers – or sleep and don’t return for the next N
milliseconds.
Calling this waiting function (or using the older curl_multi_wait() or
even doing a select() or poll() call “manually”) is crucial for a
well-behaving program. It is important to let the code go to sleep
like this when there’s nothing to do and have the system wake up it up
again when it needs to do work. Failing to do this correctly, risk
having libcurl instead busy-loop somewhere and that can make your
application use 100% CPU during periods. That’s terribly unnecessary
and bad for multiple reasons.
When ... something happens and the application for example needs to
shut down immediately, users have been asking for a way to do a wake
up call.
curl_multi_wakeup() explicitly makes a curl_multi_poll() function
return immediately. It is designed to be possible to use from a
different thread.

What consequences can be after calling an asynchronous method in deconstructer?

I am currently working on a game project that requires some data synchronization with a remote server. This data is just game state like unlocked levels or players items. So I have a singleton object that is responsible to push local data to the server by using asynchronous HTTP post request. I just can't decide when to call this method.
One idea is sending the updated game state just before closing the game. I am working with c++. Well, I know that deconstructers are not for this, but if I can do it in the deconstructer, I can be sure that all the progress is pushed to the server.
However, I can't really guess the possible consequences of calling an asynchronous method in the deconstructer. Can the application stay alive at least the response arrives for every time? Is doing something like that really bad?
Can the application stay alive at least the response arrives for every time?
No.
Is doing something like that really bad?
Yes.
At the end of a destructor call, all members are deallocated in the reverse order of allocation. If something attempts to utilize this deallocated memory (i.e. an async function) it would results in an access violation / segfault / undefined behavior depending on your compiler/OS/source.
In order to guarantee a return, you need to turn your asynchronous call into a synchronous one. Usually this can be done using a lock/notify pattern, or a simple thread join if your application is multithreaded.
It kind of depends on how your code is laid out.
There is nothing inherently wrong about calling an async method from a destructor. If you want to do something on a different thread, and you can be sure that the thread is not going to need any resources from the object being detroyed, go for it.
The issue seems to be that you want to wait for a response, and not close the game until you are positive the save state has been persisted somewhere. If after you send the async request, the main function is exited, then it is not a good thing. However, what you could do is ensure that the thread that is doing the async request is joined before you exit.
However, depending on your design, if you were going to do that, you could just have a call before your program terminates that saves the data. Eg.
int main()
{
Game g;
//Game loop
...
g.saveState();
return 0;
}

c++ How to stop all functions when a certain parameter is met

in c++ How can I stop or pause all other functions while this condition is met
else if (packet[0] == 0x5)
{
}
Basically I have a separate void function running a constant loop however if packet[0] ==0x5 i need it to stop all other threads (or pause)
Please
and
thanks
Ant
I don't think there is a direct way to stop or pause other threads (other then stopping the entire program by exit(0)). The only approach I'm aware of is a cooperative way where the threads which need to stop or pause are notified in some way and proactively act upon this notification. How the notification would look exactly depends largely on your system. One approach could be an atomic flag indicating that there is a need to act. If your threads supporting messaging, sending each one a message is probably more lightweight.
In 'stdlib.h' there is a function exit(int Status_Code) which terminates execution of whole program. You should call exit(1) .
If you want only terminate that function just use return. e.g.
if(condition_met)
{
return;
}
Maybe put all those function calls into a thread, and when your realise you need to stop those functions, kill the thread

cancelling a search using threads

I am new to multi-threading. I am using c++ on unix.
In the code below, runSearch() takes a long time and I want to be able to kill the search as soon as "cancel == true". The function cancelSearch is called by another thread.
What is the best way to solve this problem?
Thanks you..
------------------This is the existing code-------------------------
struct SearchTask : public Runnable
{
bool cancel = false;
void cancelSearch()
{
cancel = true;
}
void run()
{
cancel = false;
runSearch();
if (cancel == true)
{
return;
}
//...more steps.
}
}
EDIT: To make it more clear, say runSearch() takes 10 mins to run. After 1 min, cancel==true, then I want to exit out of run() immediately rather than waiting another 9 more mins for runSearch() to complete.
You'll need to keep checking the flag throughout the search operation. Something like this:
void run()
{
cancel = false;
while (!cancel)
{
runSearch();
//do your thread stuff...
}
}
You have mentioned that you cannot modify runSearch(). With pthreads there's a pthread_setcancelstate() function, however I don't believe this is safe, especially with C++ code that expects RAII semantics.
Safe thread cancellation must be cooperative. The code that gets canceled must be aware of the cancellation and be able to clean up after itself. If the code is not designed to do this and is simply terminated then your program will probably exhibit undefined behavior.
For this reason C++'s std::thread does not offer any method of thread cancellation and instead the code must be written with explicit cancellation checks as other answers have shown.
Create a generic method that accepts a action / delegate. Have each step be something REALLY small and specific. Send the generic method a delegate / action of what you consider a "step". In the generic method detect if cancel is true and return if true. Because steps are small if it is cancelled it shouldn't take long for the thread to die.
That is the best advice I can give without any code of what the steps do.
Also note :
void run()
{
cancel = false;
runSearch();
while (!cancel)
{
//do your thread stuff...
}
}
Won't work because if what you are doing is not a iteration it will run the entire thread before checking for !cancel. Like I said if you can add more details on what the steps do it would easier to give you advice. When working with threads that you want to halt or kill, your best bet is to split your code into very small steps.
Basically you have to poll the cancel flag everywhere. There are other tricks you could use, but they are more platform-specific, like thread cancellation, or are not general enough like interrupts.
And cancel needs to be an atomic variable (like in std::atomic, or just protected it with a mutex) otherwise the compiler might just cache the value in a register and not see the update coming from another thread.
Reading the responses is right - just because you've called a blocking function in a thread doesn't mean it magically turns into a non-blocking call. The thread may not interrupt the rest of the program, but it still has to wait for the runSearch call to complete.
OK, so there are ways round this, but they're not necessarily safe to use.
You can kill a thread explicitly. On Windows you can use TerminateThread() that will kill the thread execution. Sound good right? Well, except that it is very dangerous to use - unless you know exactly what all the resources and calls are going on in the killed thread, you may find yourself with an app that refuses to work correctly next time round. If runSearch opens a DB connection for example, the TerminateThread call will not close it. Same applies to memory, loaded dlls, and all they use. Its designed for killing totally unresponsive threads so you can close a program and restart it.
Given the above, and the very strong recommendation you not use it, the next step is to call the runSearch in a external manner - if you run your blocking call in a separate process, then the process can be killed with a lot more certainty that you won't bugger everything else up. The process dies, clears up its memory, its heap, any loaded dlls, everything. So inside your thread, call CreateProcess and wait on the handle. You'll need some form on IPC (probably best not to use shared memory as it can be a nuisance to reset that when you kill the process) to transfer the results back to your main app. If you need to kill this process, call ExitProcess on it's handle (or exit in Linux)
Note that these exit calls require to be called inside the process, so you'll need to run a thread inside the process for your blocking call. You can terminate a process externally, but again, its dangerous - not nearly as dangerous as killing a thread, but you can still trip up occasionally. (use TerminateProcess or kill for this)

Call method right after blocking call

I'm using a third party library which has a blocking function, that is, it won't return until it's done; I can set a timeout for that call.
Problem is, that function puts the library in a certain state. As soon as it enters that state, I need to do something from my own code. My first solution was to do that in a separate thread:
void LibraryWrapper::DoTheMagic(){
//...
boost::thread EnteredFooStateNotifier( &LibraryWrapper::EnterFooState, this );
::LibraryBlockingFunction( timeout_ );
//...
}
void LibraryWrapper::EnterFooState(){
::Sleep( 50 ); //Ensure ::LibraryBlockingFunction is called first
//Do the stuff
}
Quite nasty, isn't it? I had to put the Sleep call because ::LibraryBlockingFunction must definitely be called before the stuff I do below, or everything will fail. But waiting 50 milliseconds is quite a poor guarantee, and I can't wait more because this particular task needs to be done as fast as possible.
Isn't there a better way to do this? Consider that I don't have access to the Library's code. Boost solutions are welcome.
UPDATE: Like one of the answers says, the library API is ill-defined. I sent an e-mail to the developers explaining the problem and suggesting a solution (i.e. making the call non-blocking and sending an event to a registered callback notifying the state change). In the meantime, I set a timeout high enough to ensure stuff X is done, and set a delay high enough before doing the post-call work to ensure the library function was called. It's not deterministic, but works most of the time.
Would using boost future clarify this code? To use an example from the boost future documentation:
int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}
boost::packaged_task<int> pt(calculate_the_answer_to_life_the_universe_and_everything);
boost::unique_future<int> fi=pt.get_future();
boost::thread task(boost::move(pt));
// In your example, now would be the time to do the post-call work.
fi.wait(); // wait for it to finish
Although you will still presumably need a bit of a delay in order to ensure that your function call has happened (this bit of your problem seems rather ill-defined - is there any way you can establish deterministically when it is safe to execute the post-call state change?).
The problem as I understand it is that you need to do this:
Enter a blocking call
After you have entered the blocking call but before it completes, you need to do something else
You need to have finished #2 before the blocking call returns
From a purely C++ standpoint, there's no way you can accomish this in a deterministic way. That is without understanding the details of the library you're using.
But I noticed your timeout value. That might provide a loophole, maybe.
What if you:
Enter the blocking call with a timeout of zero, so that it returns immediately
Do you other stuff, either in the same thread or synchronized with the main thread. Perhaps using a barrier.
After #2 is verified to be done, enter the blocking call again, with the normal non-zero timeout.
This will only work if the library's state will change if you enter the blocking call with a zero timeout.