gpt4 book ai didi

c - 这是一个体面的自制互斥锁实现吗?批评?潜在问题?

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:19 28 4
gpt4 key购买 nike

我想知道是否有人看到任何可能导致此代码出现问题的内容。我知道我可以使用其他方法/API 调用来完成此操作,但我正在尝试为我自己的平台独立性奠定基础?/跨平台互斥框架。

显然我需要做一些#ifdef 并为 Win32 Sleep() 和 GetCurrentThreadID() 调用定义一些宏...

typedef struct aec {
unsigned long long lastaudibleframe; /* time stamp of last audible frame */
unsigned short aiws; /* Average mike input when speaker is playing */
unsigned short aiwos; /*Average mike input when speaker ISNT playing */
unsigned long long t_aiws, t_aiwos; /* Internal running total */
unsigned int c_aiws, c_aiwos; /* Internal counters */
unsigned long lockthreadid;
int stlc; /* Same thread lock count */
} AEC;

char lockecho( AEC *ec ) {
unsigned long tid=0;
static int inproc=0;
while (inproc) {
Sleep(1);
}
inproc=1;
if (!ec) {
inproc=0;
return 0;
}
tid=GetCurrentThreadId();
if (ec->lockthreadid==tid) {
inproc=0;
ec->stlc++;
return 1;
}
while (ec->lockthreadid!=0) {
Sleep(1);
}
ec->lockthreadid=tid;
inproc=0;
return 1;
}

char unlockecho( AEC *ec ) {
unsigned long tid=0;
if (!ec)
return 1;
tid=GetCurrentThreadId();
if (tid!=ec->lockthreadid)
return 0;
if (tid==ec->lockthreadid) {
if (ec->stlc>0) {
ec->stlc--;
} else {
ec->lockthreadid=0;
}
}
return 1;
}

最佳答案

不,不是,据我所知,如果没有一些低级 atomic,您无法使用纯 C 代码实现互斥锁。操作( RMWTest and Set ... 等)。在您的特定示例中,考虑如果上下文切换在第一个线程有机会设置 inproc 之前中断会发生什么,然后第二个线程将恢复并将其设置为 1,现在两个线程都“认为”它们拥有对该结构的独占访问权限。这只是您的方法可能出错的众多事情之一。

另请注意,即使线程有机会设置 inproc,也不能保证赋值是原子的(它可能在赋值变量的过程中被中断)。

关于c - 这是一个体面的自制互斥锁实现吗?批评?潜在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051633/

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