为什么makecontext / swapcontext不能与pthread_mutex_lock / pthread_mutex_unlock一起使用

时间:2011-11-17 12:34:01

标签: c linux memory gcc stack

我已成功使用 makecontext / swapcontext 来移动堆栈。但是,当我尝试将其与 pthread_mutex_lock pthread_mutex_unlock 一起使用时,我总是会收到细分错误。任何想法,为什么会这样。代码如下所示。

修改

现在我读一下swapcontext手册,

由于当前pthread实现的限制,makecontext不应该在链接pthread(3)库的程序中使用(无论是否使用线程)。

解决此问题的任何解决方法?

static const unsigned int SWAP_STACK_SIZE = 8192;
// These are globally defined variables. 
// Since each thread will have its own stack, they are defined as arrays.
static ucontext_t uctx_main[8], uctx_func[8];
static char func_stack[8][SWAP_STACK_SIZE];

// tid is thread ID here, values are 0, 1, 2, 3, etc...
if (getcontext(&uctx_func[tid]) == -1)
    handle_error("getcontext");
uctx_func[tid].uc_stack.ss_sp = func_stack[tid];
uctx_func[tid].uc_stack.ss_size = SWAP_STACK_SIZE;
uctx_func[tid].uc_link = &uctx_main[tid];
makecontext(&uctx_func[tid], (void(*)())pthread_mutex_unlock, 1, &mutex);

if (swapcontext(&uctx_main[tid], &uctx_func[tid]) == -1)
    handle_error("swapcontext");

1 个答案:

答案 0 :(得分:1)

手册页指出makecontext将参数传递为int类型。如果你在64位Linux上,那么指针将是64位,而int将是32位,并且奇怪的东西将开始发生。