作为作业的一部分,我试图创建一个像 pthreads 这样的用户级线程库。
为了处理线程之间的上下文切换,我使用“swapcontext”函数。在使用它之前,我必须使用“makecontext”函数创建一个上下文。 “makecontext”需要一个具有返回类型的函数指针void
和参数类型(void)
.
然而,线程函数必须是以下类型void* thread_func (void*)
有没有办法进行类型转换?或者还有其他方法可以在用户级别进行上下文切换吗?
通过将函数的地址转换为不同的原型并通过结果指针调用它来调用具有不兼容原型的函数是非法的:
void *my_callback(void *arg) { ... }
void (*broken)(void *) = (void (*)(void *)) my_callback;
broken(some_arg); // incorrect, my_callback returns a `void *`
你能做的就是传递给makecontext
您自己的回调将调用thread_func
并忽略它的返回值。仅用于调用另一个函数的小函数有时称为蹦床 http://en.wikipedia.org/wiki/Trampoline_%28computing%29.
/* return type is compatible with the prototype of the callback received
by makecontext; simply calls the real callback */
static void trampoline(int cb, int arg)
{
void *(*real_cb)(void *) = (void *(*)(void *)) cb;
void *real_arg = arg;
real_cb(real_arg);
}
int my_pthread_create(void *(*cb)(void *), void *arg)
{
ucontext_t *ucp;
...
/* For brevity treating `void *` as the same size as `int` -
DO NOT USE AS-IS.
makecontext exposes an annoyingly inconvenient API that only
accepts int arguments; correct code would deconstruct each
pointer into two ints (on architectures where pointer is
larger than int) and reconstruct them in the trampoline. */
makecontext(ucp, trampoline, 2, (int) cb, (int) arg);
...
}
为了获得奖励积分,您可以修改蹦床以存储void *
回调函数返回的值在堆栈上,并且具有相当于pthread_join()
检索它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)