【发布时间】:2018-01-16 03:09:43
【问题描述】:
处理信号SIGALARM时出现分段错误。
这是我的代码。
class UThread{
public:
UThread(){}
~UThread(){
signal(SIGALRM,SIG_IGN);
for(size_t i=0;i<thread_list.size();i++){
delete thread_list[i]->uc_stack.ss_sp;
delete thread_list[i];
thread_list[i]=NULL;
}
}
int create_thread(void (*callback)(void *),void *args){
ucontext_t *new_context= new ucontext_t;
assert(getcontext(new_context) != -1);
new_context->uc_stack.ss_sp=new char[1024];
new_context->uc_stack.ss_size=1024;
new_context->uc_flags=0;
new_context->uc_link=0;
assert(new_context->uc_stack.ss_sp!=NULL);
makecontext(new_context,(void (*)())callback,1,args);//make a context
size_t n=thread_list.size();
//find a position to save the pointer.
int i=0;
for(;i<n;i++){
if(thread_list[i]==NULL)
break;
}
if(i<n)
thread_list[i]=new_context;
else{
thread_list.push_back(new_context);
}
return i;
}
void start_thread(){
ucontext_t *main_context= new ucontext_t;
getcontext(main_context);
thread_list.push_back(main_context);
struct sigaction sa;
sa.sa_handler=schedule;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask,SIGALRM);
sigaction(SIGALRM,&sa,NULL);
struct itimerval tick;
tick.it_value.tv_sec = 0;
tick.it_value.tv_usec = 1;
tick.it_interval.tv_sec = 0;
tick.it_interval.tv_usec = 1000;//send a SIGALRM
setitimer(ITIMER_REAL,&tick,NULL);
}
private:
static void schedule(int signo){//deal with the signal
int last_id=current_id;
int n=thread_list.size();
int i=rand()%n;//get a random number.
while(thread_list[i]==NULL){
i=rand()%n;
}
current_id=i;
if(thread_list[last_id]==NULL){//if it has been cancelled,just setcontext.
setcontext(thread_list[i]);
return;
}
swapcontext(thread_list[last_id],thread_list[current_id]);//swap the context.
}
static int current_id;
static vector<ucontext_t*> thread_list;
};
vector<ucontext_t*> UThread::thread_list;
int UThread::current_id=0;
这是类定义的。如果我调用两个以上的函数,它会出现分段错误。
void f2(void *){
const char *buf="I am f2.\n";;
while(true){
write(STDOUT_FILENO,buf,strlen(buf));
}
}
void f3(void *){
const char *buf="I am------- f3.\n";
while(true){
write(STDOUT_FILENO,buf,strlen(buf));
}
}
int main(){
UThread t;
t.start_thread();
int thread_id2=t.create_thread(f2,NULL);
int thread_id3=t.create_thread(f3,NULL);
const char *buf="I am main.\n";
while(true){
write(STDOUT_FILENO,buf,strlen(buf));
}
return 0;
}
这是函数调用
如果我在主函数中删除t.create_thread(f3,NULL);之一,它将成功运行而不会出错。但是如果我在主函数中添加两个t.create_thread(func,NULL);,则在swapcontext(thread_list[last_id],thread_list[current_id]);完成后会出现分段错误。
【问题讨论】:
-
在信号处理程序中可以执行的操作受到限制。我不确定你的
schedule函数是异步安全的。 -
@Barmar 我认为调度函数是异步安全的,因为我在处理信号之前屏蔽了 start_thread 中的信号。但我不明白我是否删除了 t.create_thread(func,NULL ) 它将成功运行
标签: c++ linux segmentation-fault signals ucontext