gpt4 book ai didi

c - pthread_cond_wait() 不会让 CPU 休眠吗?

转载 作者:太空狗 更新时间:2023-10-29 16:07:33 26 4
gpt4 key购买 nike

全部

我有一个关于 pthread_cond_wait() 的问题。简而言之,我在一个进程中创建了两个 POSIX 线程,如果我执行以下代码,为什么 cpu 利用率满了?

我在上面做实验,如果我把 bool isNodeConnect3 前面的注释去掉,该程序似乎没有问题,CPU 利用率几乎为 0%,换句话说,theads 将进入休眠状态并且不占用 CPU 资源,这就是我想要的。

这是一个数据对齐问题吗?也许吧,但我不这么认为,因为我用“#pragma pack(push,1) ... #pragma (pop)”将我的结构括起来你能给我建议吗??

环境主机操作系统是 win7/intel 64 位, guest 操作系统是 ubuntu 10.04LTS将“处理器核心数:4”提供给 guest 操作系统以下是我的测试代码,您可以通过
构建并运行它gcc -o program1 program1.c -pthread && ./program1获取 CPU 利用率为 25%。结果取决于您的设置。

非常感谢。

代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <stdbool.h>


#pragma pack(push,1)
struct BUFF_TX{
pthread_mutex_t mutex_lock;
pthread_cond_t more;
};

struct AtreeNode{
struct BUFF_TX buff_tx;

bool isNodeConnect;
bool isNodeConnect1;
bool isNodeConnect2;
// bool isNodeConnect3; // important

pthread_t thrd_tx;

};


struct AtreeNode treeNode[2];
int tmp[2];

#pragma (pop)


void Thread_TX(int *nodeIdx)
{
int idx = *nodeIdx;

while(1)
{

printf("Thread %d enter mutex lock...\n", idx);
pthread_mutex_lock(&treeNode[idx].buff_tx.mutex_lock);
while(1)
{
if(idx==0)
{
printf("idx==0 wait...\n");
pthread_cond_wait(&(treeNode[0].buff_tx.more), &treeNode[idx].buff_tx.mutex_lock);
}
else if(idx==1)
{
printf("idx==1 wait...\n");
pthread_cond_wait(&(treeNode[1].buff_tx.more), &treeNode[idx].buff_tx.mutex_lock);
}
else
printf("err\n");

}
pthread_mutex_unlock(&treeNode[idx].buff_tx.mutex_lock);
printf("Thread %d leave mutex lock...\n", idx);

}

}




int main(int argc, char *argv[])
{
int i;
int ret;

tmp[0] = 0;
tmp[1] = 1;


for(i=0; i<2; i++)
{
if(pthread_cond_init(&treeNode[i].buff_tx.more, NULL) != 0)
{
printf("cond %d init fail.\n", i);
exit(EXIT_FAILURE);
}

if(pthread_mutex_init(&treeNode[i].buff_tx.mutex_lock, NULL) != 0)
{
printf("mutex lock %d init fail.\n", i);
exit(EXIT_FAILURE);
}
}

for(i=0; i<2; i++)
{
ret = pthread_create(&treeNode[i].thrd_tx, NULL, (void *)Thread_TX, (void *)(&tmp[i]));
if(ret)
{
printf("pthread_create thrd_tx %d err\n", i);
return false;
}
}

pthread_join(treeNode[0].thrd_tx, NULL);
pthread_join(treeNode[1].thrd_tx, NULL);

exit(EXIT_SUCCESS);
}

最佳答案

删除 #pragma pack(1) 并忘记您曾经听说过它。您的问题是您传递了一个指向 pthread_cond_wait 的无效指针。 pthread_cond_t 有特定的对齐要求,您正在创建不一定符合该要求的对象,因此它们的地址无法传递给 pthread_cond_wait。另见 https://sourceware.org/bugzilla/show_bug.cgi?id=16549由于未捕获无效指针使用而被移动到针对 GCC 的错误报告中得到解决。

您应该能够通过在 strace -f 下运行您的程序并查看 futex 系统调用失败并显示 EINVAL 或类似的。

关于c - pthread_cond_wait() 不会让 CPU 休眠吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22166474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com