函数原型:
int pthread_attr_setaffinity_np(pthread_attr_t *attr, size_t cpusetsize,const cpu_set_t *cpuset);
用于设置线程的 CPU 亲和性(CPU Affinity)。
它允许将线程绑定到特定的 CPU 核心或 CPU 集合上,以控制线程在哪些 CPU 上运行。
函数原型:
int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize,const cpu_set_t *cpuset);
用于设置线程的 CPU 亲和性(CPU Affinity)。
它允许将线程绑定到特定的 CPU 核心或 CPU 集合上,以控制线程在哪些 CPU 上运行。
本示例演示了如何在创建线程时限制其只能在 cpu1 上运行。
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>void *thread_func(void *arg)
{usleep(10000);// 获取当前线程的 CPU 亲和性cpu_set_t cpuset;CPU_ZERO(&cpuset);pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);// 打印当前线程绑定的 CPUfor (int i = 0; i < CPU_SETSIZE; i++) {if (CPU_ISSET(i, &cpuset)) {printf("thread is running on cpu %dn", i);}}return NULL;
}int main() {pthread_t tid;pthread_attr_t attr;pthread_attr_init(&attr);// 创建线程并设置其只能在 cpu1 上运行cpu_set_t mask;CPU_ZERO(&mask);CPU_SET(1, &mask);pthread_attr_setaffinity_np(&attr, sizeof(mask), &mask);pthread_create(&tid, &attr, thread_func, NULL);pthread_attr_destroy(&attr);pthread_join(tid, NULL);return 0;
}
本示例演示了如何在创建线程后限制其只能在 cpu0 1 2 上运行。
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>void *thread_func(void *arg)
{usleep(10000);// 获取当前线程的 CPU 亲和性cpu_set_t cpuset;CPU_ZERO(&cpuset);pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);// 打印当前线程绑定的 CPUfor (int i = 0; i < CPU_SETSIZE; i++) {if (CPU_ISSET(i, &cpuset)) {printf("thread is running on cpu %dn", i);}}return NULL;
}int main() {// 创建线程并设置其只能在 cpu0 1 2 上运行pthread_t tid;cpu_set_t mask;CPU_ZERO(&mask);CPU_SET(0, &mask);CPU_SET(1, &mask);CPU_SET(2, &mask);pthread_create(&tid, NULL, thread_func, NULL);pthread_setaffinity_np(tid, sizeof(mask), &mask);pthread_join(tid, NULL);return 0;
}
示例1
中的方式进行 cpu 亲和性的设置。本文发布于:2024-01-27 18:22:03,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063509211869.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |