与 qsort 相比,可重入 qsort_r 函数的可移植性如何?
qsort_r()
是 qsort()
的可重入版本,它接受一个额外的“thunk”参数并将其传递到比较函数中,我希望能够在可移植的 C 代码中使用它。 qsort()
是 POSIX 且无处不在,但 qsort_r()
似乎是 BSD 扩展。作为一个具体问题,Windows C 运行时中是否存在或具有等效项?
qsort_r()
is the re-entrant version of qsort()
which takes an additional 'thunk' argument and passes it into the compare function and I'd like to be able to use it in portable C code. qsort()
is POSIX and everywhere but qsort_r()
seems to be a BSD extension. As a specific question, does this exist or have an equivalent in the Windows C runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我尝试编写一个可移植版本的 qsort_r / qsort_s (称为 sort_r),并举例说明。我还将此代码放入 git 存储库 (https://github.com/noporpoise/sort_r)
示例用法:
编译/run/output:
我已经在 mac & 上进行了测试linux。如果您发现错误/改进,请更新此代码。您可以随意使用此代码。
I've attempted to write a portable version of qsort_r / qsort_s (called sort_r) shown with an example. I've also put this code in a git repo (https://github.com/noporpoise/sort_r)
Example usage:
Compile/run/output:
I've tested on mac & linux. Please update this code if you spot mistakes / improvement. You are free to use this code as you wish.
对于 Windows,您将使用
qsort_s
: http://msdn.microsoft.com/en-us/library/4xc60xas(VS.80).aspx显然,关于 BSD 和 GNU 的
qsort_r
版本不兼容存在一些争议,因此在生产代码中使用它时要小心: http://sourceware.org /ml/libc-alpha/2008-12/msg00003.html顺便说一句,
_s
代表“安全”,_r
代表“可重入” ”,但两者都意味着有一个额外的参数。For Windows you would use
qsort_s
: http://msdn.microsoft.com/en-us/library/4xc60xas(VS.80).aspxApparently there is some controversy about BSD and GNU having incompatible versions of
qsort_r
, so be careful about using it in production code: http://sourceware.org/ml/libc-alpha/2008-12/msg00003.htmlBTW, the
_s
stands for "secure" and the_r
stands for "re-entrant", but both mean that there's an extra parameter.任何可移植性标准都没有指定它。另外,我认为将其称为 qsort 的“线程安全”版本是错误的。标准 qsort 是线程安全的,但 qsort_r 有效地允许您传递闭包作为比较函数。
显然在单线程环境中,使用全局变量和qsort可以达到相同的结果,但这种用法不是线程安全的。线程安全的另一种方法是使用线程特定的数据,并让比较函数从线程特定的数据中检索其参数(对于 POSIX 线程,
pthread_getspecific
,或__thread
gcc 和即将推出的 C1x 标准中的变量)。It's not specified in any portability standard. Also I think it's a mistake to call it a "thread-safe" version of
qsort
. The standardqsort
is thread-safe, butqsort_r
effectively allows you to pass a closure as your comparison function.Obviously in a single-threaded environment, you can achieve the same result with a global variable and
qsort
, but this usage will not be thread-safe. A different approach to thread-safety would be to use thread-specific data and have your comparison function retrieve its parameter from the thread-specific data (pthread_getspecific
with POSIX threads, or__thread
variables in gcc and the upcoming C1x standard).