Mark下调试中出现的诡异现象,在程序中添加一个内存管理模块后,导致了其他线程占用高cpu,
该线程的线程栈如下(该线程主要功能就是处理模块间的消息):
#0 0x00007f81b7d48da2 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
#1 0x0000000000416a80 in MsgQueue::Dequeue (this=0x13af1961, item=...) at ../public/xx/xxx.h:109
#2 0x0000000000416198 in module_message (arg=0xb0deb0 <ModuleMgr+4848>) at ../public/xx/xxx.cpp:17
#3 0x00007f81b7d44e65 in start_thread () from /lib64/libpthread.so.0
#4 0x00007f81b5e6288d in clone () from /lib64/libc.so.6
查阅资料发现有网友(https://bbs.csdn.net/topics/390787479)也出现过类似问题,其调用pthread_cond_timedwait代码如下,问题是pthread_cond_timedwait的最后参数outtime赋值错误导致,错误语句:
outtime.tv_nsec = now.tv_usec,两边的单位不一样,一个是纳秒,一个是微秒。这样赋值会使得pthread_cond_timewait的超时时间比当前时间还小。
gettimeofday(&now, NULL);
now.tv_usec += ms * 1000;
if(now.tv_usec >= 1000000)
{
now.tv_sec += now.tv_usec / 1000000;
now.tv_usec %= 1000000;
}
outtime.tv_nsec = now.tv_usec;
outtime.tv_sec = now.tv_sec;
int ret = pthread_cond_timedwait(&cond, &mutex, &outtime);
而我这里也这么赋值,但是tv_usec*1000后来赋值的,还是出现高cpu,后面各种调试还是高
t.tv_sec = now.tv_sec+1;
t.tv_nsec = now.tv_usec*1000;
小伙伴调试这个部分代码时就是各种coredump,到我这里就是高cpu(说明一下:小伙伴和我使用代码的平台不一样,当然编译器和运行平台不一样),修改了内存管理模块头文件的对齐方式(原来是1字节对齐,修改为4字节对齐)后,不挂了,我这尝试修改对齐cpu也神奇的降下来了
神奇的字节对齐
后来查阅资料,人家说互斥锁一字节对齐导致的,不知道为什么