日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

绑定线程到特定CPU处理器

發布時間:2025/3/21 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 绑定线程到特定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处理器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。