0

我已经定义了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试图初始化堆中尚未分配的东西。

4

1 回答 1

0

指针悬空,这ucontext_t* cur就是它 swapcontext 崩溃的原因。您可以分配一个有效值 ( new ucontext_t),但最好设置它的类型ucontext_t而不是指针。同样也很重要,thread.tctx也不需要保留thread.sp指针。

但是,C++11std::thread是您尝试做的更好的替代方案,这将是正确的 C++ 方法。另外,如果您想学习新知识,我建议您改用 std::thread 。这里有一个很好的教程:https ://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/

顺便说一句,在您的示例getcontext(n->tctx);中,还调用了未初始化tctx的程序,并且在程序结束时您有很多未释放的内存...

于 2016-03-24T21:36:52.607 回答