我收到一个奇怪的错误。我实现了这两个功能:
int flag_and_sleep(volatile unsigned int *flag)
{
int res = 0;
(*flag) = 1;
res = syscall(__NR_futex, flag, FUTEX_WAIT, 1, NULL, NULL, 0);
if(0 == res && (0 != (*flag)))
die("0 == res && (0 != (*flag))");
return 0;
}
int wake_up_if_any(volatile unsigned int *flag)
{
if(1 == (*flag))
{
(*flag) = 0;
return syscall(__NR_futex, flag, FUTEX_WAKE, 1, NULL, NULL, 0);
}
return 0;
}
并通过运行两个 Posix 线程来测试它们:
static void die(const char *msg)
{
fprintf(stderr, "%s %u %lu %lu\n", msg, thread1_waits, thread1_count, thread2_count);
_exit( 1 );
}
volatile unsigned int thread1_waits = 0;
void* threadf1(void *p)
{
int res = 0;
while( 1 )
{
res = flag_and_sleep( &thread1_waits );
thread1_count++;
}
return NULL;
}
void* threadf2(void *p)
{
int res = 0;
while( 1 )
{
res = wake_up_if_any( &thread1_waits );
thread2_count++;
}
return NULL;
}
在 thread2 进行了一百万次左右的迭代后,我得到了断言:
./a.out 0 == res && (0 != (*flag)) 1 261129 1094433
这意味着系统调用 - 因此 do_futex() - 返回 0。Man 说只有在被 do_futex(WAKE) 调用唤醒时才应该这样做。但是在我进行 WAKE 调用之前,我将标志设置为 0。这里的标志似乎仍然是 1。
这是Intel,意思是强内存模型。因此,如果在线程 1 中我看到线程 2 中的系统调用的结果,我还必须看到调用之前线程 2 中的写入结果。
标志和指向它的所有指针都是易失的,所以我看不出 gcc 如何无法读取正确的值。
我很困惑。
谢谢!