尝试将swaptext()转换为存储在队列中的struct成员时出现Seg-fault

时间:2016-03-24 19:58:34

标签: c++ ucontext

我已经定义了一个名为thread的结构,其成员名为ucontext* tctx

在一个名为create_thread()的函数中,我在堆上创建一个线程对象并定义其每个成员(包括ucontext对象的成员)。然后我将指向该线程对象的指针添加到队列容器中。

当我弹出队列以交换到线程的上下文时,我就会出错。我不确定为什么会这样。

以下是完整代码:

#include <iostream> 
#include <queue>
#include <ucontext.h> 

#define STACK_SIZE 262144

using namespace std; 

typedef struct thread
{
   int thread_id; 
   ucontext* tctx; 
   char* sp;  
}thread; 

int thread_id; 
ucontext_t* ctx1; //Unused, currently 
ucontext_t* cur; 
queue<thread*> ready_queue; 

/* Function Declaration */
thread* create_thread(int,int); 
void foo1(int); 


int main(int argc, char** argv)
{
   cout << " PROGRAM START ***** \n";

   /* Create 'i' number of threads */  
   for(int i = 0; i < 2; i++) 
   {
      cout << "\nready_queue size before creating thread = " << ready_queue.size() << endl;
      cout << "Calling create thread ... id=" << i << endl;
      create_thread(i, i*1000);    
      cout << "ready_queue size after creating thread = " << ready_queue.size() << endl; 
   }

   cout << " \t>> THREADS CREATED \n"; 
   cout << " \t>> SWITCHING CONTEXT \n";   


   /* Save current context to cur, swap context to first thread in queue */ 
   swapcontext(cur, ready_queue.front()->tctx); //Seg fault!

   cout << " PROGRAM TERMI ***** \n"; 
   return 0; 
}


thread* create_thread(int id, int arg)
{
   static int num_threads = 0; 

   /* Create a new thread struct, ucontxt for the thread, and put in ready queue */  
   thread* n = new thread;
   getcontext(n->tctx); 
   n -> thread_id = id; 
   n -> tctx = new ucontext_t;
   n -> sp   = new char[STACK_SIZE];   

   n->tctx->uc_stack.ss_sp = n->sp; 
   n->tctx->uc_stack.ss_size = STACK_SIZE; 
   n->tctx->uc_stack.ss_flags = 0; 
   n->tctx->uc_link = NULL;    
   makecontext(n->tctx, (void(*)()) foo1, 1, arg); //Thread shall call foo() with argument 'arg' 

   /* Push new thread into ready_queue */ 
   ready_queue.push(n);

   num_threads++; 
   cout << "Thread #" << num_threads << " was created. Thread.ID[" << id << "]\n"; 

   return n; 
}


//Application function
void foo1(int arg)
{
   cout << "Calling from foo1(). I have " << arg << "!\n"; 
}

编辑:

我注意到,如果我在getcontext(n->tctx);之后调用n -> tctx = new ucontext_t;,问题就解决了。似乎问题可能是getcontext试图初始化堆中尚未分配的东西。

1 个答案:

答案 0 :(得分:0)

ucontext_t* cur指针悬空,这就是swapcontext崩溃的原因。您可以分配有效值(new ucontext_t),但最好使其类型ucontext_t而不是指针。对于thread.tctx也同样重要,也不需要将thread.sp作为指针。

但是,C ++ 11有std::thread,这是你尝试做的更好的选择,这将是正确的C ++方法。另外,如果你想学习新东西,我建议你专注于std :: thread。这里有一个很好的教程:https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/

顺便说一句,在您的示例中getcontext(n->tctx);也会在未初始化的tctx上调用,并且在程序结束时您有很多不同意的内存...