You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么我的std::thread线程会在CPU核心间频繁切换?

为什么我的std::thread(运行OpenCV摄像头显示逻辑)一直在CPU核心间切换?

最近我开始尝试使用std::thread,并用OpenCV写了一个在独立线程中显示摄像头画面的小程序,纯粹是为了学习研究。不过我发现这个线程似乎一直在不同的CPU核心之间切换,从效率和性能角度来看,这种切换的开销感觉得不偿失。我想知道导致这种现象的根本原因是什么?

补充信息:

  • 我是StackOverflow新手,如果有遗漏的关键信息,请随时告诉我。
  • 系统环境:Ubuntu

代码示例:

#include <stdio.h>
#include <opencv2/opencv.hpp> //openCV functionality
#include <time.h> //timing functionality
#include <thread>
using namespace cv;
using namespace std;
void webcam_func(){
 Mat image;
 namedWindow("Display window");
 VideoCapture cap(0);
 if (!cap.set(CAP_PROP_AUTO_EXPOSURE , 10)){
 std::cout <<"Exposure could not be set!" <<std::endl;
 //return -1 ;
 }
 if (!cap.isOpened()) {
 cout << "cannot open camera";
 }
 int i = 0;
 while (i < 1000000) {
 cap >> image;
 Size s = image.size();
 int rows = s.height;
 int cols = s.width;
 imshow("Display window", image);
 double fps = cap.get(CAP_PROP_FPS);
 //cout << "Frames per second using video.get(CAP_PROP_FPS) : " << fps << endl;
 //cout <<"The height of the video is " <<rows <<endl;
 //cout <<"The width of the video is " <<cols <<endl;
 std::thread::id this_id = std::this_thread::get_id();
 std::cout << "thread id --> " << this_id <<std::endl;
 waitKey(25);
 i++ ;
 std::cout <<"Counter value " <<i <<std::endl;
 }
}
int main() {
 std::thread t1(webcam_func);
 while(true){
 }
 return 0;
}

内容的提问来源于stack exchange,提问作者Geo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:03:13