绑定线程到特定CPU处理器
生活随笔
收集整理的這篇文章主要介紹了
绑定线程到特定CPU处理器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考這篇文章?
http://blog.chinaunix.net/uid-27761170-id-5050258.html
?
代碼如下:
#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;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; } 這段代碼將使myfun線程在所有cpu中依次執行一段時間,在我的四核cpu上,執行結果為??: ?? ? ? system has 4 processor(s)?? ? ? ? ?? ? ? thread 1095604544 is running in processor 0?? ? ? ? ?? ? ? thread 1095604544 is running in processor 1?? ? ? ? ?? ? ? thread 1095604544 is running in processor 2?? ? ? ? ?? ? ? thread 1095604544 is running in processor 3? 在一些嵌入式設備中,運行的進程線程比較單一,如果指定進程線程運行于特定的cpu核,減少進程、線程的核間切換,有可能可以獲得更高的性能。轉載于:https://www.cnblogs.com/charlesblc/p/6263468.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的绑定线程到特定CPU处理器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 建立空间参考 ISpatialRefer
- 下一篇: python 安装scrapy,open