linux 下进程和线程指定CPU运行
生活随笔
收集整理的這篇文章主要介紹了
linux 下进程和线程指定CPU运行
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
大概的介紹一下linux 的指定CPU運行,包括進程和線程,這個只是最基本的方法,看一下基本就會了,至于其他的進程間通信和線程同步的話,這里暫不做任何介紹。
算了,還是比較整體的介紹一下如何去學習這個吧。
linux下的top命令是可以查看當前的cpu的運行狀態,具體參數自己去查,這里只介紹與標題相關的,按1可以查看系統有多少個CPU,以及每個CPU的運行狀態。可是如何查看線程的CPU呢???top -Hp pid,pid就是你當前程序的進程號,如果是多線程的話,是可以查看進程內所有線程的CPU和內存使用情況。
pstree可以查看主次線程,同樣的pstree -p pid。可以查看進程的線程情況。
taskset這個其實才是重點,可以查看以及設置當前進程或線程運行的CPU(設置親和力)。
taskset -pc pid,查看當前進程的cpu,當然有的時候不只是一個,taskset -pc cpu_num pid ,cpu_num就是設置的cpu。
這樣的話基本的命令和操作其實大家都知道了,接下來就是在代碼中完成這些操作,并通過命令去驗證代碼的成功率。
進程制定CPU運行:
#include<stdlib.h> #include<stdio.h> #include<sys/types.h> #include<sys/sysinfo.h> #include<unistd.h> #define __USE_GNU #include<sched.h> #include<ctype.h> #include<string.h>int main(int argc, char* argv[]) {//sysconf獲取有幾個CPUint num = sysconf(_SC_NPROCESSORS_CONF);int created_thread = 0;int myid;int i;int j = 0;//原理其實很簡單,就是通過cpu_set_t進行位與操作cpu_set_t mask;cpu_set_t get;if (argc != 2){printf("usage : ./cpu num\n");exit(1);}myid = atoi(argv[1]);printf("system has %i processor(s). \n", num);//先進行清空,然后設置掩碼CPU_ZERO(&mask);CPU_SET(myid, &mask);//設置進程的親和力if (sched_setaffinity(0, sizeof(mask), &mask) == -1){printf("warning: could not set CPU affinity, continuing...\n");}while (1){CPU_ZERO(&get);//獲取當前進程的親和力if (sched_getaffinity(0, sizeof(get), &get) == -1){printf("warning: cound not get cpu affinity, continuing...\n");}for (i = 0; i < num; i++){if (CPU_ISSET(i, &get)){printf("this process %d is running processor : %d\n",getpid(), i);}}}return 0; }
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sched.h>void *myfun(void *arg) {cpu_set_t mask;cpu_set_t get;char buf[256];int i;int j;//同樣的先去獲取CPU的個數int num = sysconf(_SC_NPROCESSORS_CONF);printf("system has %d processor(s)\n", num);for (i = 0; i < num; i++) {CPU_ZERO(&mask);CPU_SET(i, &mask);//這個其實和設置進程的親和力基本是一樣的if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {fprintf(stderr, "set thread affinity failed\n");}CPU_ZERO(&get);if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {fprintf(stderr, "get thread affinity failed\n");}for (j = 0; j < num; j++) {if (CPU_ISSET(j, &get)) {printf("thread %d is running in processor %d\n", (int)pthread_self(), j);}}j = 0;while (j++ < 100000000) {memset(buf, 0, sizeof(buf));}}pthread_exit(NULL); }int main(int argc, char *argv[]) {pthread_t tid;if (pthread_create(&tid, NULL, (void *)myfun, NULL) != 0){fprintf(stderr, "thread create failed\n");return -1;}pthread_join(tid, NULL);return 0; }
總結
以上是生活随笔為你收集整理的linux 下进程和线程指定CPU运行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1.什么是机器学习
- 下一篇: Linux 下的Core Dump