Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » U++ Library support » U++ MT-multithreading and servers » AsyncWork, IsFinished() may not be working properly
Re: AsyncWork, IsFinished() may not be working properly [message #54429 is a reply to message #54428] Sat, 18 July 2020 09:59 Go to previous messageGo to previous message
Oblivion is currently offline  Oblivion
Messages: 1093
Registered: August 2007
Senior Contributor
Hello JeyCi,

And welcome to the U++ forums!

Note that when the worker is removed from the array in the first example, the item count is also decreased by 1.
This obviously invalidates the indices, so the code breaks the for loop and starts it all over again (from 0).
Hence the "two or more zeros" in the log output. It might give the impression of race condition, but it is not. (If that's the problem.)

(The reason is that the first example was about a problem in IsFinished(). It was always returning true.
The example did not rely on those indices for its purpose, so I didn't care to make it more correct...)



Please try this one instead:

CONSOLE_APP_MAIN
{
	StdLogSetup(LOG_FILE|LOG_COUT);
	
	Array<AsyncWork<int>> workers;
	
	for(int i = 0; i < 4; i++) {
		workers.Add() = Async([=]{ LOG("Started, worker #" << i); Sleep(500); return i; });
	}
	
	while(!workers.IsEmpty())
		for(int i = 0; i < workers.GetCount(); i++) {
			auto& w = workers[i];
			if(w.IsFinished()) {
				LOG("Stopped, worker #" << w.Get());
				workers.Remove(i);
				break;
			}
		}
}



Quote:

I found below code seems working good


Yes, that works, because, unlike the "non-blokcking" first example, this one has a "blocking" loop:

	for (auto &fut : workers) {
		LOG("Stopped, worker #" << fut.Get());
	}


The Get() method will wait the worker to finish its job unless it is alreay finished. So it is "blocking".


Best regards,
Oblivion


[Updated on: Sat, 18 July 2020 10:29]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Skylark session verification
Next Topic: How do I create a loop for a window to react to volatile changes to a global variable?
Goto Forum:
  


Current Time: Sun Apr 28 20:31:22 CEST 2024

Total time taken to generate the page: 0.05714 seconds