假设我们有以下代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void guarantee(bool cond, const char *msg) {
if (!cond) {
fprintf(stderr, "%s", msg);
exit(1);
}
}
bool do_shutdown = false; // Not volatile!
pthread_cond_t shutdown_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t shutdown_cond_mutex = PTHREAD_MUTEX_INITIALIZER;
/* Called in Thread 1. Intended behavior is to block until
trigger_shutdown() is called. */
void wait_for_shutdown_signal() {
int res;
res = pthread_mutex_lock(&shutdown_cond_mutex);
guarantee(res == 0, "Could not lock shutdown cond mutex");
while (!do_shutdown) { // while loop guards against spurious wakeups
res = pthread_cond_wait(&shutdown_cond, &shutdown_cond_mutex);
guarantee(res == 0, "Could not wait for shutdown cond");
}
res = pthread_mutex_unlock(&shutdown_cond_mutex);
guarantee(res == 0, "Could not unlock shutdown cond mutex");
}
/* Called in Thread 2. */
void trigger_shutdown() {
int res;
res = pthread_mutex_lock(&shutdown_cond_mutex);
guarantee(res == 0, "Could not lock shutdown cond mutex");
do_shutdown = true;
res = pthread_cond_signal(&shutdown_cond);
guarantee(res == 0, "Could not signal shutdown cond");
res = pthread_mutex_unlock(&shutdown_cond_mutex);
guarantee(res == 0, "Could not unlock shutdown cond mutex");
}
符合标准的 C/C++ 编译器是否可以do_shutdown
在调用时将 的值缓存在寄存器中pthread_cond_wait()
?如果不是,哪些标准/条款可以保证这一点?
编译器可以假设知道pthread_cond_wait()
不修改do_shutdown
. 这似乎不太可能,但我知道没有标准可以阻止它。
实际上,是否有任何 C/C++ 编译器do_shutdown
在调用 ? 时将 的值缓存在寄存器中pthread_cond_wait()
?
编译器保证哪些函数调用不会缓存cross的值do_shutdown
?很明显,如果函数是在外部声明的并且编译器无法访问它的定义,它就不能对其行为做出任何假设,因此它无法证明它没有访问do_shutdown
. 如果编译器可以内联函数并证明它不能访问,那么即使在多线程设置中do_shutdown
它也可以缓存吗?do_shutdown
同一个编译单元中的非内联函数怎么样?