小编典典

CPU相似性掩码(将线程放入不同的CPU)

linux

我有4个线程,并且尝试将线程1设置为在CPU 1上运行,线程2在CPU
2上运行,等等。但是,当我在下面运行代码时,亲和力掩码返回正确的值,但是当我执行sched_getcpu()在线程上,它们都返回它们正在CPU 4上运行。

有人知道我的问题在这里吗?

提前致谢!

#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sched.h>
#include <errno.h>

void *pthread_Message(char *message)
{
    printf("%s is running on CPU %d\n", message, sched_getcpu());
}

int main()
{
    pthread_t thread1, thread2, thread3, thread4;
    pthread_t threadArray[4];
    cpu_set_t cpu1, cpu2, cpu3, cpu4;
    char *thread1Msg = "Thread 1";
    char *thread2Msg = "Thread 2";
    char *thread3Msg = "Thread 3";
    char *thread4Msg = "Thread 4";
    int thread1Create, thread2Create, thread3Create, thread4Create, i, temp;

    CPU_ZERO(&cpu1);
    CPU_SET(1, &cpu1);
    temp = pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpu1);
    printf("Set returned by pthread_getaffinity_np() contained:\n");
    for (i = 0; i < CPU_SETSIZE; i++)
        if (CPU_ISSET(i, &cpu1))
            printf("CPU1: CPU %d\n", i);

    CPU_ZERO(&cpu2);
    CPU_SET(2, &cpu2);
    temp = pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpu2);
    for (i = 0; i < CPU_SETSIZE; i++)
        if (CPU_ISSET(i, &cpu2))
            printf("CPU2: CPU %d\n", i);

    CPU_ZERO(&cpu3);
    CPU_SET(3, &cpu3);
    temp = pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpu3);
    for (i = 0; i < CPU_SETSIZE; i++)
        if (CPU_ISSET(i, &cpu3))
            printf("CPU3: CPU %d\n", i);

    CPU_ZERO(&cpu4);
    CPU_SET(4, &cpu4);
    temp = pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpu4);
    for (i = 0; i < CPU_SETSIZE; i++)
        if (CPU_ISSET(i, &cpu4))
            printf("CPU4: CPU %d\n", i);

    thread1Create = pthread_create(&thread1, NULL, (void *)pthread_Message, thread1Msg);
    thread2Create = pthread_create(&thread2, NULL, (void *)pthread_Message, thread2Msg);
    thread3Create = pthread_create(&thread3, NULL, (void *)pthread_Message, thread3Msg);
    thread4Create = pthread_create(&thread4, NULL, (void *)pthread_Message, thread4Msg);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    pthread_join(thread4, NULL);

    return 0;
}

阅读 458

收藏
2020-06-07

共1个答案

小编典典

您正在尝试设置未初始化的线程的相似性。

编辑:好的,让我给您更多信息:

不要混合使用线程句柄(存储在pthread_t变量中的东西)和它们代表的内容(在某个地方运行的执行线程)。您试图做的是使用需要线程对象的API在启动之前设置线程的属性。碰巧pthread_create会创建对象并同时开始执行,因此尝试使用pthread_setaffinity_np不是正确的方法(如果要
更改 当前正在运行的线程的相似性,这将非常有用)。

但是… pthread_create具有一个属性参数(您正在向其传递NULL)。这将存储有关如何创建线程的信息。

亲和力是您可以通过该参数设置的属性之一。请参阅手册页文档pthread_attr_initpthread_attr_setaffinity_np以了解其精确性

2020-06-07