为什么xlib会干扰XNVCtrl调用?

时间:2019-10-24 18:32:30

标签: c multithreading pthreads nvidia xlib

我正在使用C线程进行练习。我的程序必须不断(定期)轮询可用的GPU内存(和其他信息),同时能够处理X事件。问题是当我调用XNVCTRLQueryTargetAttribute时,程序冻结并吃掉1个核心的100%。这是代码,既简化,又有漏洞。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <X11/Xlib.h>
#include "NVCtrl/NVCtrl.h"
#include "NVCtrl/NVCtrlLib.h"

Display *display;
pthread_t t1, t2;

void *run(void *t)
{
    XEvent e;
    int total;
    int gpu = 0;

    if(t == &t1) {
        while(1) {
            XNVCTRLQueryTargetAttribute(display, NV_CTRL_TARGET_TYPE_GPU, gpu, 0,
                NV_CTRL_TOTAL_DEDICATED_GPU_MEMORY, &total);
            fprintf(stderr, "total memory: %d\n", total);
            sleep(1);
        }
    }
    else {
        XNextEvent(display, &e);
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    if(!(display = XOpenDisplay(NULL)))
        return 1;

    pthread_create(&t1, NULL, run, (void *) &t1);
    pthread_create(&t2, NULL, run, (void *) &t2);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    XCloseDisplay(display);

    return EXIT_SUCCESS;
}

我使用的命令。 要编译程序,您需要Nvidia图形卡和专有驱动程序

cc -lpthread -lX11 -L/usr/X11R6/lib -o foo foo.c /usr/lib/libXNVCtrl.so

当我注释掉XNextEvent(display, &e);行或带有XNVCTRLQueryTargetAttribute调用的行时,每秒都会在终端上显示“总内存:0”。否则就什么也没有。

我刚刚在没有线程的情况下进行了测试,没有看到很高的CPU使用率。将以下代码移至main

XNVCTRLQueryTargetAttribute(display, NV_CTRL_TARGET_TYPE_GPU, gpu, 0,
    NV_CTRL_TOTAL_DEDICATED_GPU_MEMORY, &total);
fprintf(stderr, "total memory: %d\n", total);
XNextEvent(display, &e);
sleep(1);

打印消息“总内存:1996”,然后XNextEvent阻止永恒(因为没有侦听器)。我想问题是我不太了解线程,也许结合了动态链接。我怀疑这很重要,但是无论如何,英伟达驱动程序:435.21-11。

0 个答案:

没有答案