我定义了一个名为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";
}
编辑:
我注意到,如果我在n -> tctx = new ucontext_t;
之后调用getcontext(n->tctx);
,问题就解决了。问题似乎是getcontext
试图初始化堆中尚未分配的东西。
ucontext_t* cur
指针悬空,这就是它swapcontext崩溃的原因。您可以分配一个有效的值(new ucontext_t
),但最好使其类型为ucontext_t
,而不是指针。CCD_ 10也是如此,并且也不需要将CCD_ 11保持为指针。
然而,C++11有std::thread
,这是一个更好的选择,可以替代您正在尝试做的事情,这将是正确的C++方法。此外,如果你想学习一些新的东西,我建议你把重点放在std::thread上。这里有一个很好的教程:https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
顺便说一句,在您的示例中,getcontext(n->tctx);
也是在未初始化的tctx
上调用的,并且在程序结束时有很多未释放的内存。。。