用户级线程上下文切换:如何检测线程何时在C中阻塞? [英] User-level threads context switching: How to detect when a thread is blocking in C?

查看:152
本文介绍了用户级线程上下文切换:如何检测线程何时在C中阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的那样,C语言中是否有一种方法可以检测用户级线程何时在内核级线程之上运行,例如pthread是否已阻止(或即将阻止)I/O?

As the title suggests, is there a way in C to detect when a user-level thread running on top of a kernel-level thread e.g., pthread has blocked (or about to block) for I/O?

我的用例如下:我需要在多线程环境中执行任务(在内核线程(例如pthreads)之上).这些任务基本上是可以同步的用户功能,并且可以在其中使用阻塞操作.我需要在实现中隐藏延迟.因此,我正在探索将任务实现为用户级线程的想法,以便更好地控制它们的执行上下文,这样,当任务阻塞或同步时,我会上下文切换到其他就绪任务(即,为任务实现自己的调度程序)用户级线程).因此,几乎可以充分利用操作系统每个内核线程的时间量.

My use case is as follows: I need to execute tasks in a multithreaded environment (on top of kernel threads e.g., pthreads). The tasks are basically user functions that can be synchronized and may use blocking operations within. I need to hide latency in my implementation. So, I am exploring the idea of implementing the tasks as user-level threads for better control of their execution context such that, when a task blocks or synchronizes, I context-switch to other ready tasks (i.e., implementing my own scheduler for the user-level threads). Consequently, almost the full use of the OS’s time quantum per kernel thread can be achieved.

推荐答案

曾经有执行此操作的代码,例如 GNU pth .它通常被放弃,因为它不能很好地工作,并且我们现在有更好的选择.您有两种选择:

There used to be code that did this, for example GNU pth. It's generally been abandoned because it just doesn't work very well and we have much better options now. You have two choices:

1)如果有OS帮助,则可以使用OS机制. Windows为此提供了操作系统帮助,IOCP调度使用了它.

1) If you have OS help, you can use the OS mechanisms. Windows provides OS help for this, IOCP dispatching uses it.

2)如果没有操作系统帮助,则必须将所有阻止操作转换为调用您的调度程序而不是阻止的非阻止操作.因此,例如,如果有人调用socket,则您将拦截该调用并将套接字设置为非阻塞.当他们调用read时,您将拦截该呼叫,并且如果他们收到将阻止"指示,则可以安排在操作可能成功时恢复并安排另一个线程.

2) If you have no OS help, then you have to convert all blocking operations into non-blocking ones that call your dispatcher rather than blocking. So, for example, if someone calls socket, you intercept that call and set the socket non-blocking. When they call read, you intercept that call and if they get a "would block" indication, you arrange to resume when the operation might succeed and schedule another thread.

您可以查看GNU pth,以了解如何使选项2起作用.但请注意,GNU pth 已报告的所有错误自废弃以来从未修复过.它将为您提供有关如何在协作的用户空间线程环境中实现互斥和睡眠之类的想法.但实际上不要使用代码.

You can look at GNU pth to see how you might make option 2 work. But be warned, GNU pth is full of reported bugs that have never been fixed since it was abandoned. It will give you an idea of how to implement things like mutexes and sleeps in a cooperative user-space threading environment. But don't actually use the code.

这篇关于用户级线程上下文切换:如何检测线程何时在C中阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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