使用setjump loopjump在线程中跳转的问题

使用setjumploopjump在线程中跳转的问题
使用setjump到另一个线程中跳转,跳转成功了,后面的代码不执行了
#define_CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
jmp_bufbuf;
void*print_a(void*);
void*print_b(void*);
//线程A方法
void*print_a(void*a){
for(inti=0;i<5;++i){
sleep(1);
printf("aaaa\n");
intjmpret=setjmp(buf);
if(!jmpret){
printf("!jmpret\n");
}else{
printf("继续执行线程1\n");
}
}
returnNULL;
}
//线程B方法
void*print_b(void*b){
for(inti=0;i<5;++i){
sleep(1);
printf("bbbb\n");
if(i==3){
printf("进入线程2\n");
longjmp(buf,1);
}
}
returnNULL;
}
intmain(){
pthread_tt0;
pthread_tt1;
//创建线程A
if(pthread_create(&t0,NULL,print_a,NULL)==-1){
printf("failtocreatepthreadt0\n");
exit(1);
}
if(pthread_create(&t1,NULL,print_b,NULL)==-1){
printf("failtocreatepthreadt1\n");
exit(1);
}
//等待线程结束
void*result;
if(pthread_join(t0,&result)==-1){
printf("failtorecollectt0\n");
exit(1);
}else{
printf("t0success\n");
}
if(pthread_join(t1,&result)==-1){
printf("failtorecollectt1\n");
exit(1);
}else{
printf("t1success\n");
}
getchar();
return0;
}
主线程的getchar也不执行了这是为何?
慕虎7371278
浏览 331回答 2
2回答

一只萌萌小番薯

讲真,我没想到还能这么用....setjmp/longjmpisimplementedbysavingtheregister(includingstackandcodepointeretc)whenfirstpassed,andrestoringthemjumping.当线程b通过longjmp跳到print_a时,它的栈帧和线程a的栈帧所在的内存就是一个地方了(原来栈的内存没人管)。当线程a退出时,自然要弹出所有栈帧,那么线程b之后对栈访问就是对非法内存的访问了。就像你把双胞胎中的弟弟的头嫁接到哥哥身上,哥哥变成了连体婴儿,哥哥挂掉之后,弟弟也活不成了,反之也是

慕桂英3389331

longjmp不能跨线程。C117.13.2.1/2:Thelongjmpfunctionrestorestheenvironmentsavedbythemostrecentinvocationofthesetjmpmacrointhesameinvocationoftheprogramwiththecorrespondingjmp_bufargument.Iftherehasbeennosuchinvocation,oriftheinvocationwasfromanotherthreadofexecution,orifthefunctioncontainingtheinvocationofthesetjmpmacrohasterminatedexecutionintheinterim,oriftheinvocationofthesetjmpmacrowaswithinthescopeofanidentifierwithvariablymodifiedtypeandexecutionhasleftthatscopeintheinterim,thebehaviorisundefined
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript