gpt4 book ai didi

c++ - 立即终止线程

转载 作者:行者123 更新时间:2023-11-28 07:57:32 26 4
gpt4 key购买 nike

我已经实现了一个并行运行的线程。我想要的是每当用户按下一个按钮时,说“p”,线程应该立即停止。

我的代码是:

bool b=false;
pthread_t thread1=0;

void handlerforfunc3(void* arg)
{
b=true;
cout<<"Handler exited"<<endl; //this was not output when 'in the while loop' stopped printing'
}

void handler()
{
cout<<"PROCESS HAS ENTERED THE HANDLER"<<endl;

rrscheduler(ready, job);
}

void* func3(void *arg)
{
pthread_cleanup_push(handlerforfunc3, NULL);
timer(arg); //timer() is a function called in the thread
handler();
pthread_cleanup_pop(0);
}


void rrscheduler()
{
pthread_create(&thread1, NULL, func3, (void*)(arg1));
}

int main()
{
while(1)
{
char c=cin.get();
switch(c)
{
case 'p':
if(thread1!=0)
{
pthread_cancel(thread1);
while(!b)
{
cout<<"in the while loop"<<endl;
}
} //thread1!=0

b=false;
rrscheduler();

}//switch ends
} //while ends
}

发生的事情是,每当我尝试通过按“p”来打断时,屏幕上都会充满“在 while 循环中”,并持续显示,然后在 3-4 秒后停止。并且 < em>在那之后既不显示'handler exited'也不调用rrscheduler。此外,在显示 while 循环中的 '' 时,还会显示来自 timer() 函数的语句。

我的问题是:
1.如何让线程立即结束执行
2.为什么我们退出while循环后(b为真后)main中的rrscheduler不执行?

最佳答案

当您尝试取消它时,线程似乎正在调用 timer()。计时器完成后,它应该取消。根据pthread_cancel() man page :

The pthread_cancel() function requests that thread be canceled. The target threads cancelability state and type determines when the cancellation takes effect. When the cancellation is acted on, the cancellation cleanup handlers for thread are called...

因此,取消不会立即生效。根据 timer() 的实现,可能无法立即取消线程。

main() 中的 rrscheduler() 函数在您退出 while 循环后不会执行,因为 thread1 从未分配给 0。您应该按如下方式分配它:

if(thread1!=0)
{
pthread_cancel(thread1);
while(!b)
{
cout<<"in the while loop"<<endl;
}
thread1 = 0; // <== assigning to 0 here
} //thread1!=0

关于c++ - 立即终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12393532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com