在 Linux 上的 C# .Net Core 6 中设置线程关联

问题描述 投票:0回答:1

我正在尝试将线程的线程亲和力设置为 Ubuntu Linux 上的特定内核(使用 WSL)。 我编写了一个 C 程序来验证原则上它是否有效。 但当我尝试设置与 pthread_setafinity_np 的亲和力时,我的 C# 程序因分段错误而结束。

顺便说一句:我必须在 Windows 或 Linux 上为此使用不同的代码,这不是我所理解的平台无关:-(

这是我的 C# 程序

using System;
using System.Runtime.InteropServices;
using System.Threading;

class Program
{
  [DllImport("libc.so.6")]
  static extern int pthread_setaffinity_np(IntPtr thread, ulong cpusetsize, IntPtr cpuset);


  static void Main()
  {
    // Create a new thread
    Thread thread = new Thread(MyThreadFunction);

    // Start the thread
    thread.Start();

    // Wait for the thread to complete
    thread.Join();
  }

  static void MyThreadFunction()
  {
   
    // Get the current thread ID
    IntPtr threadId = new IntPtr(Thread.CurrentThread.ManagedThreadId);

    // Create a CPU set with CPU 0
    ulong cpuMask = 1;
    IntPtr cpuSet = Marshal.AllocHGlobal(Marshal.SizeOf(cpuMask));
    Marshal.StructureToPtr(cpuMask, cpuSet, false);

    // Set the CPU affinity of the thread
    int result = pthread_setaffinity_np(threadId, (ulong)Marshal.SizeOf(cpuMask), cpuSet);

    if (result != 0)
    {
      Console.WriteLine($"Failed to set thread affinity: {result}");
    }

    Marshal.FreeHGlobal(cpuSet);

 
  }```
c# linux multithreading pthreads
1个回答
0
投票

ManagedThreadId 不是操作系统线程 id,您应该 dllimport gettid()。

© www.soinside.com 2019 - 2024. All rights reserved.