Results 1 to 14 of 14

Thread: [RESOLVED] Core Affinity

Threaded View

  1. #7
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,958

    Re: Core Affinity

    Quote Originally Posted by Shaggy Hiker View Post
    Yeah, all that's true or likely so. Having more threads than there are cores, defeats the purpose....and now that I think about it, I might have more cores on this system than I thought. I was thinking I had four, but six would be more likely. I'll have to look at some point.

    My understanding of Tasks was that they were lighter weight than creating full threads, and would be managed by the OS to only start up when there was a core free to work on. That's not what is happening, based on what I am seeing, unless they are all on the same core...which looks likely. In that case, using Tasks in the way I was doing was essentially the same as running each one sequentially, with the added overhead of Task management.

    I have realized that there is a much better way to do this, which splits the work up more meaningfully, but I'm reluctant to try it, because it would mean that some of the nicer features of the UI would be rendered meaningless. Therefore, I think I won't change it. The time taken is not too steep a price to pay for having a nice UI.
    IIRC Tasks are delegated to the ThreadPool when created using Task.Run - this allows the ThreadPool itself to balance the number of running threads.

    If you run the following Console app
    Code:
    Imports System.Runtime.InteropServices
    
    Module Program
    
           Sub Main()
    
            Dim tasks As New List(Of Task)
            For i = 0 To 100
                Dim x = i
                tasks.Add(Task.Run(Sub() DoStuff(x)))
            Next
    
            Task.WaitAll(tasks.ToArray)
    
        End Sub
    
        Private Async Sub DoStuff(i As Integer)
            Console.WriteLine($"Starting Task {i} on Thread {Environment.CurrentManagedThreadId}, on cpu {GetCurrentProcessorNumber()}, {ThreadPool.PendingWorkItemCount()} Items queued")
            Task.Delay(5000).Wait()
            Console.WriteLine($"Ending Task {i} on Thread {Environment.CurrentManagedThreadId}, on cpu {GetCurrentProcessorNumber()}, {ThreadPool.PendingWorkItemCount()} Items queued")
    
        End Sub
    
    
        <DllImport("Kernel32.dll")>
        Public Function GetCurrentProcessorNumber() As Integer
        End Function
    
    End Module
    You will see the output creates multiple tasks, some using the same thread, and the threads are using different cpus / cores. Note that a thread may also move between cores.
    Last edited by PlausiblyDamp; May 2nd, 2024 at 06:18 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width