我正在评论一个线程本地存储很好的答案,并回忆起另一个关于我认为的异常的信息性讨论
throw 块中的执行环境唯一的特殊之处是异常对象被 rethrow 引用。
将两个和两个放在一起,不会在其主函数的函数捕获块内执行整个线程,并为其注入线程本地存储吗?
它似乎工作正常,虽然速度很慢。这本小说还是有特色的?是否有另一种解决问题的方法?我最初的前提是正确的吗?get_thread
您的平台会产生什么样的开销?优化的潜力是什么?
#include <iostream>
#include <pthread.h>
using namespace std;
struct thlocal {
string name;
thlocal( string const &n ) : name(n) {}
};
struct thread_exception_base {
thlocal &th;
thread_exception_base( thlocal &in_th ) : th( in_th ) {}
thread_exception_base( thread_exception_base const &in ) : th( in.th ) {}
};
thlocal &get_thread() throw() {
try {
throw;
} catch( thread_exception_base &local ) {
return local.th;
}
}
void print_thread() {
cerr << get_thread().name << endl;
}
void *kid( void *local_v ) try {
thlocal &local = * static_cast< thlocal * >( local_v );
throw thread_exception_base( local );
} catch( thread_exception_base & ) {
print_thread();
return NULL;
}
int main() {
thlocal local( "main" );
try {
throw thread_exception_base( local );
} catch( thread_exception_base & ) {
print_thread();
pthread_t th;
thlocal kid_local( "kid" );
pthread_create( &th, NULL, &kid, &kid_local );
pthread_join( th, NULL );
print_thread();
}
return 0;
}
这确实需要定义从 派生的新异常类thread_exception_base
,用 初始化基类get_thread()
,但总的来说,这不像是周日早上失眠的低效……</p>
编辑:看起来 GCC对in进行了三个调用。编辑:对堆栈、环境和可执行格式进行了大量令人讨厌的内省,以找到我在第一次演练中错过的块。这看起来高度依赖于平台,因为 GCC 正在从操作系统调用一些。大约 4000 个周期的开销。我想它还必须遍历类层次结构,但这可以保持在控制之下。pthread_getspecific
get_thread
catch
libunwind