1

我已经设法让我的 pthreads 程序正常工作。基本上我正在尝试手动设置 4 个线程的亲和性,以便线程 1 在 CPU 1 上运行,线程 2 在 CPU 2 上运行,线程 3 在 CPU 3 上运行,线程 4 在 CPU 4 上运行。

编译后,我的代码适用于几个线程,但不适用于其他线程(似乎线程 1 从不工作),但运行相同的编译程序几次不同的时间会给我不同的结果。

例如:
hao@Gorax:~/Desktop$ ./a.out
线程 3 正在 CPU 3 上运行
pthread_setaffinity_np: Invalid argument
线程 2 正在 CPU 2 上运行
hao@Gorax:~/Desktop$ ./a.out
线程 2正在 CPU 2 上运行
pthread_setaffinity_np: 参数无效
pthread_setaffinity_np: 参数无效
线程 3 正在 CPU 3 上运行
线程 3 正在 CPU 3 上运行
hao@Gorax:~/Desktop$ ./a.out
线程 2 正在 CPU 2 上运行
pthread_setaffinity_np: 无效参数
线程 4 正在 CPU 4 上运行
线程 4 正在 CPU 4 上运行
hao@Gorax:~/Desktop$ ./a.out
pthread_setaffinity_np: Invalid argument

我的问题是“为什么会发生这种情况?另外,为什么该消息有时会打印两次?”

这是代码:

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

#define handle_error_en(en, msg) \
               do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

void *thread_function(char *message)
{
    int s, j, number;
    pthread_t thread;
    cpu_set_t cpuset;

    number = (int)message;
    thread = pthread_self();    
    CPU_SET(number, &cpuset);

    s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
    if (s != 0)
    {
        handle_error_en(s, "pthread_setaffinity_np");
    }

    printf("Thread %d is running on CPU %d\n", number, sched_getcpu());

    exit(EXIT_SUCCESS);
}

int main()
{
    pthread_t thread1, thread2, thread3, thread4;
    int thread1Num = 1;
    int thread2Num = 2;
    int thread3Num = 3;
    int thread4Num = 4;
    int thread1Create, thread2Create, thread3Create, thread4Create, i, temp;

    thread1Create = pthread_create(&thread1, NULL, (void *)thread_function, (char *)thread1Num);
    thread2Create = pthread_create(&thread2, NULL, (void *)thread_function, (char *)thread2Num);
    thread3Create = pthread_create(&thread3, NULL, (void *)thread_function, (char *)thread3Num);
    thread4Create = pthread_create(&thread4, NULL, (void *)thread_function, (char *)thread4Num);

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

    return 0;
}
4

1 回答 1

2

第一个 CPU 是CPU 0而不是CPU 1。所以你要改变你的threadNums:

int thread1Num = 0;
int thread2Num = 1;
int thread3Num = 2;
int thread4Num = 3;

您应该cpuset以这种方式使用 CPU_ZERO() 宏进行初始化:

CPU_ZERO(&cpuset);
CPU_SET(number, &cpuset);

也不要从线程调用 exit() ,因为它会停止整个进程及其所有线程:

退出(EXIT_SUCCESS);  
返回0;// 改用它或调用 pthread_exit()
于 2010-04-02T04:49:20.543 回答