Thread and priority


#1

Hello everybody,

I want to create two threads with of priority difference. Fortunately there is a parameter in the function thread which allow to handler the priority with 1 = priority max and 10 = priority min.

This is my code :
import kotlin.concurrent.thread

val t2 = thread(start = false, priority = 10){
        	println("running from thread(): ${Thread.currentThread()}")
            for(i in 1..1000){
                    println("t2 = $i")
            }}
val t1 = thread(start = false, priority = 1){
        	println("running from thread(): ${Thread.currentThread()}")
            for(i in 1..1000){
                    println("t1 = $i")
            }}
fun main(args: Array<String>) {
    
	t1.start()
    t2.start()
    t1.join()
    t2.join()
    
}

the problem is that there is no priority, we can see on the terminal the value of ‘i’ of t1 and t2 in same time whereas I should see first the value ‘i’ of t1 because it is more priority and then the value ‘i’ of t2

thank you for yours answers


#2

Did you have a multi core processor?
You can use two cores together.


#3

As far as I understand thread priority (and I am no expert), priority does not mean that any thread is guaranteed to run faster. I mean any of your processing cores runs at a certain clock speed and this wont be affected by the thread priority. However, if your computer is using a lot of CPU power threads with a higher priority are get more processing power.

If you want to guarantee that one thread is executing faster than another you have to look at other ways of doing that. You could use some sort of state saying, thread 1 is only allowed to execute the next bit of thread 2 reached point x, or you could add delays using the Thread.sleep function.