同一进程中的线程有多独立? [英] How independent are threads inside the same process?

查看:112
本文介绍了同一进程中的线程有多独立?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,这可能是一个非常新手的问题,但是我真的没有多线程编程的经验,而且我还没有完全理解线程与进程相比的工作原理.

Now, this might be a very newbie question, but I don't really have experience with multithreaded programming and I haven't fully understood how threads work compared to processes.

当机器上的某个进程挂起时,例如正在等待某个永远不会出现的IO或类似的东西,我可以杀死并重新启动它,因为其他进程不受影响,并且仍然可以操作我的终端.当然,这非常明显.

When a process on my machine hangs, say it's waiting for some IO that never comes or something similar, I can kill and restart it because other processes aren't affected and can, for example, still operate my terminal. This is very obvious, of course.

我不确定进程中的线程是否相同:如果一个进程挂起,其他进程是否不受影响?换句话说,我可以运行一个看门狗"线程来监视其他线程,例如杀死并重新创建挂起的线程吗?例如,如果我有一个线程池,我不想被偶尔的挂断消耗掉.

I'm not sure whether it is the same with threads inside a process: If one hangs, are the others unaffected? In other words, can I run a "watchdog" thread which supervises the other threads and, for example kill and recreate hanging threads? For example, if I have a threadpool that I don't want to be drained by occasional hangups.

推荐答案

线程是独立的,但是进程和线程之间是有区别的,也就是说,在进程的情况下,操作系统所做的不仅仅是杀了它.清除后也会清除.

Threads are independent, but there's a difference between a process and a thread, and that is that in the case of processes, the operating system does more than just "kill" it. It also cleans up after it.

如果您开始杀死似乎已挂起的线程,则很可能将资源锁定并保持类似状态,如果您对某个进程执行相同的操作,操作系统将为您关闭该线程.

If you start killing threads that seems to be hung, most likely you'll leave resources locked and similar, something that the operating system would close for you if you did the same to a process.

例如,如果您打开一个文件进行写入,然后开始生成数据并将其写入该文件,并且由于某种原因该线程现在挂起,则杀死该线程将使该文件保持打开状态,并且很可能已锁定,直到关闭整个程序.

So for instance, if you open a file for writing, and start producing data and write it to the file, and this thread now hangs, for whatever reason, killing the thread will leave the file still open, and most likely locked, up until you close the entire program.

因此,对您的问题的真正答案是:不,您不能用困难的方式杀死线程.

So the real answer to your question is: No, you can not kill threads the hard way.

如果您只是简单地要求一个线程关闭,那是不同的,因为该线程仍处于控制状态,可以在终止之前清理和关闭资源,但是调用诸如"KillThread"之类的API函数是不好的.

If you simply ask a thread to close, that's different because then the thread is still in control and can clean up and close resources before terminating, but calling an API function like "KillThread" or similar is bad.

这篇关于同一进程中的线程有多独立?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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