线程块操作

时间:2017-11-08 21:45:18

标签: multithreading

我问了两个关于使用线程读取文件的问题(12),这样主线程就不会被阻止。我的问题不是编写和启动一个线程,我的问题是我不明白什么操作阻塞。我之前被告知,从文件读取是一个阻塞,在我的第二个例子中使用for循环是阻塞。在查看一段代码时,我真的不明白为什么甚至发现它。

所以我的问题显然是,你如何发现或确定一个操作何时阻塞一个线程,你如何修复它?

1 个答案:

答案 0 :(得分:0)

So my question obviously is, how do you spot or determine when an operation is blocking a thread

There's no magic way to do it; in general you have to read the documentation for whatever functions you call in order to get an idea about whether they are guaranteed to return quickly or whether they might block for an extended period of time.

If you're looking at a running program and want to know what its threads are currently doing, you can either watch them using a debugger, or insert print statements at various locations so that you can tell (by seeing what text gets printed to stdout and what text doesn't) roughly where the thread is at and what it is doing.

, and how do you fix it?

Blocking is not "broken", so there's nothing to fix. Blocking is intentional behavior, so that e.g. when you call a function that reads from disk, it can provide you back some useful data when it returns. (Consider an alternative non-blocking read, which would always return immediately, but in most cases wouldn't be able to provide you with any data, since the hard drive had not had time to load in any data yet -- not terribly useful).

That said, for network operations you can set your socket(s) to non-blocking mode so that calls to send(), recv(), etc are guaranteed never to block (they will return an error code instead). That only works for networking though; most OS's don't support non-blocking I/O for disk access.