如何从外部阻止线程 [英] How Do I Stop A Thread From Outside Of It

查看:89
本文介绍了如何从外部阻止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main() {
       
        pthread_t t;
        int k;
      pthread_create(&t,NULL, timer, NULL) // thread is running well.

if(cin >> k) goto point; // when is enter value thread should be closed
        point:
    closegraph(); 
   TerminateThread(&t,0);
   
cout <<"Exiting......";
        getch();
    }

推荐答案

一个全局变量或更好的事件,在线程中检查。通过这种方法,你可以做一些像句柄或内存的清理,并终止干净和平滑。
A global variable or better an event which is checked in the thread. By that method you can do some cleanup like handles or memory and terminate clean and smooth.


'严重'是答案 - 它的危险 - 最好的方法是有一个事件句柄,检查在线程的工作过程/循环中周期性地,如果它被标记(通过从线程外部发信号/提出它),从
'badly' is the answer - its dangerous - the best way is to have perhaps an eventhandle, check that periodically in the thread's working procedure/loop, and if its flagged (by signalling/raising it from outside the thread), exit the thread cleanly from within

if(cin >> k) goto point; // when is enter value thread should be closed
        point:



如果语句在收到某些输入时始终为true,那么 goto 没有任何意义。你真的应该学会编写没有 goto 语句的代码,它们会导致意想不到的结果。


The if statement will always be true when some input is received so the goto serves no purpose. And you really should learn to write code without goto statements, they can cause unintended results.


这篇关于如何从外部阻止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆