2

I have an interesting problem, it seems simple but I can seem to find any solutions to it online or on stackoverflow.

I have a program which generates threads to search down paths of a maze in order to find a way out. Upon reaching a dead end a thread returns to the junction it came from and marks the direction as dead so no other thread looks down that way. Similarly, upon reaching the way out the thread returns and marks the direction it came from as golden, if a thread finds a golden path it ignores everything else and follows the golden directions to the exit and terminates.

My problem is if a thread finds the exit I want it to return all the way to the beginning junction marking the golden directions on the way before being booted off the processor for using up it's share of processor time. Currently a thread which has found the exit can get halfway through marking the way out when it's quantum of time on the processor runs out and it gets kicked out of the processor for the time being, so some threads still exploring the earlier parts of the maze wander about wasting time when they could be on their way out.

How do I ensure that a thread 't' which has just found the exit, stays on the processor until it terminates itself.

Thanks in advance.

SHolmes
  • 178
  • 13
  • 3
    `when it gets booted off` - what on earth does this mean? – Scary Wombat Aug 26 '16 at 05:44
  • Oh hell sorry, didn't realise how vague that comment was, hopefully my edit clears up what I mean. – SHolmes Aug 26 '16 at 06:00
  • 1
    Sorry maybe I am being naive, but can you not change your code so that if a thread finds the `exit`, then it sets its `quantum of time` so it does not get `booted off`? – Scary Wombat Aug 26 '16 at 06:03
  • can you increase the thread's priority, so that it ensures that this thread which keeps moving forward, actually gets scheduled immediately instead of others, preemptive? – a3.14_Infinity Aug 26 '16 at 06:06
  • You need to post some code. – matt Aug 26 '16 at 06:12
  • @ScaryWombat As far as I am aware you cannot personally set how long a thread stays on the processor for at the software level, that's something that the operating system does and is quite fundamental to scheduling processes and such. It's an interesting read on a side note, I did a paper about it and it was great. – SHolmes Aug 26 '16 at 06:14
  • @a3.14_Infinity That's what I'm doing currently but the JavaDoc doesn't give any assurance to how long the process stays on the processor for. The JavaDoc for MAX_PRIORITY vaguely says "The maximum priority that a thread can have." – SHolmes Aug 26 '16 at 06:18
  • I guess you are meaning for `android` and not java in general – Scary Wombat Aug 26 '16 at 06:18
  • BTW, what would happen if the Thread spawned another Thread? – Scary Wombat Aug 26 '16 at 06:18
  • One simple solution would be to have a thread manager, which would start your threads in a while loop but only if a certain flag has been set. This thread could be set to true when a particular thread starts and to false when it ends (actually this would probably be the last line of code in the thread's execute method). – dsp_user Aug 26 '16 at 06:19
  • @matt I'm not sure what code would be useful in this sense, there's no problem with the code per se, I'm just forward thinking in terms of maximising the efficiency of what I'm going to write. I've only written half of it so far, but I like to plan ahead. – SHolmes Aug 26 '16 at 06:23
  • @ScaryWombat No this is just for the good old fasioned Java on a computer. If a thread spawned another thread it's not a problem, it'll get scheduled by the operating system like a normal thread would once it signals it is ready to run. This is actually what my threads are going to do, each thread has a limit to how many threads it can make, when it reaches a junction it splits off into multiple threads to explore. As long as it has available children left 'to spend' of course. – SHolmes Aug 26 '16 at 06:26
  • Another solution would be to use the synchronized keyword. While this will not prevent threads from running simultaneously , it will prevent access to a particular method or a block of code marked as synchronized, which may be good enough for you. – dsp_user Aug 26 '16 at 06:28
  • @dsp_user I'm not a 100% sure of what you mean by starting my threads in a loop? It's not the starting I'm having trouble with or managing my threads, I just need to, once a certain condition has been met, ensure it doesn't leave the processor until it finishes what it is doing completely. – SHolmes Aug 26 '16 at 06:32
  • @dsp_user I don't think you quite understand the extent of my issue, I'm fine with the concurrency part of this problem, I'm using semaphores to avoid key race conditions. I need to find a way to keep a thread on a processor core even if it's quantum is up. – SHolmes Aug 26 '16 at 06:35
  • Threads pretty much run to completion. It isn't clear why you think otherwise. You are using a lot of terms that aren't relevant/meaningful. A concrete example would be useful to see what you are actually having an issue with. – matt Aug 26 '16 at 06:35
  • If you want your background thread(s) to complete without ever switching to the main thread, I think it's impossible. But you can control how your background threads execute. – dsp_user Aug 26 '16 at 06:41
  • what @SHolmes wants is that, the thread which reaches the exit, should have a priority similar to a garbage collector thread, become that special thread, so that it is not evicted out. I checked some questions on so. looks like you need a special platform to solve this problem - RTOS, specially designed VM that respects priorities - check this: http://stackoverflow.com/questions/21206655/how-to-change-garbage-collection-threads-priority – a3.14_Infinity Aug 26 '16 at 06:42
  • The garbage collector thread has a very low priority and what he wants is just the opposite. – dsp_user Aug 26 '16 at 06:47
  • @matt Right I understand that but imagine a huge maze and I allow my program to generate 50 threads in order to explore it but the machine my program is running on only has 4 cores. It's an inefficient amount of overhead I know but I'm just using it as an example. I can only have 4 threads running at one time so the operating system scheduler has to rotate the threads in a fair fashion so they each get a turn searching their respective paths. My issue is when a thread finds the exit it may get kicked off the processor for another thread before it can tell everyone it has found the way out. – SHolmes Aug 26 '16 at 06:49
  • @matt Meaning every thread has to wait, unneccessarily, for that thread, which found the way, to be put back on the processor and mark the way out for every other thread to follow. How can I mark a thread as special and should not be taken off the processor for any reason? – SHolmes Aug 26 '16 at 06:49
  • @a3.14_Infinity gets what I mean, so from what I'm reading on this post it's pretty much out of the realms of possibility for my implementation, thanks for the help though this has certainly turned out to be a larger more intricate problem that I had hoped for! – SHolmes Aug 26 '16 at 06:51
  • @SHolmes: there could be a possibility, stretching a little bit.. not sure.. need to read up few things. surely people would have stumbled your scenario and might have found some alternative to do this.. – a3.14_Infinity Aug 26 '16 at 06:55

1 Answers1

4

There's no way you can guarantee programmatically that your thread stays on the processor until it finished its work. Thread scheduling is an OS prerogative and it follows rules of fairness when distributes quanta of time between threads.

If we look deeper, the processor itself is allowed to decide on what thread could wait for a while (for instance, if it's asking for a memory part that is not cached yet and it will take long to deliver those data to the cache), but these delays are minor.

Overall, your task looks like an overengineering. Unless your maze is immensely huge that marking the golden path takes so long time that it really matters (it usually takes microseconds at worst on modern computers to change the state of rather large chunks of memory, even in multithreaded environment), and you really count micro- and nanoseconds, all you need is to develop a good maze-walking algorithm, optimise it, find what number of threads works best for you and let the JVM, OS and CPU do the rest. They are good enough at doing their job even without so deep tuning.

If even after that you still want to do something about it (maybe just out of curiosity), you could use the following strategy: Create a special thread with the highest possible priority and keep it ready. When one of your working threads finds the golden path, delegate the task of marking it to that high-priority thread. Though it won't guarantee you that the thread cannot be got kicked out of the processor, the quanta of its time will be larger.

In Java, you can do it by means of ExecutorService:

private final ExecutorService executor =
        Executors.newFixedThreadPool(1, r -> {
            Thread thread = new Thread(r, "golden-path-marker");
            thread.setPriority(Thread.MAX_PRIORITY);
            return thread;
        });
executor.prestartCoreThread();

And later, when you find the path:

executor.submit(() -> {
    // Mark the golden path here
});

But be aware that switching between threads is time consuming, so your maze must be really big and marking the path must be really time-consuming for you to gain something from this approach.

Andrew Lygin
  • 6,077
  • 1
  • 32
  • 37
  • Thanks @AndrewLygin I thought that might be the case. A very in depth answer, from what you have said it seems a bridge too far for the solution I need to produce and would only produce negligible improvements, if any. I'll leave scheduling to the OS from now on. – SHolmes Aug 26 '16 at 07:06