title: Why makecontext/swapcontext does not work with pthread_mutex_lock/pthread_mutex_unlock
body: <p>I have used <strong>makecontext/swapcontext</strong> successfully for shifting the stack. However, when I try to use it with <strong>pthread_mutex_lock</strong> or <strong>pthread_mutex_unlock</strong>, I always receive segmentation fault. Any idea, why is that so. The code is shown below.</p>
  
  <h2>EDIT</h2>
  
  <p>Now I read from the swapcontext manual,</p>
  
  <p><em>Due to limitations in the current pthread implementation, makecontext should not be used in programs which link against the pthread(3) library (whether threads are used or not).</em></p>
  
  <p>Any workaround to solve this?</p>
  
  <pre><code>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(&amp;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 = &amp;uctx_main[tid];
  makecontext(&amp;uctx_func[tid], (void(*)())pthread_mutex_unlock, 1, &amp;mutex);
  
  if (swapcontext(&amp;uctx_main[tid], &amp;uctx_func[tid]) == -1)
      handle_error("swapcontext");
  </code></pre>