libgit2 - 前景与背景

libgit2 - Foreground vs. Background

我正在使用 libgit2 API 编写 Qt 应用程序。某些功能显然放在后台线程中:

git_remote_fetch

其他的很容易在前台线程中内联完成(即,在单击的插槽中进行验证):

git_reference_is_valid_name

但是,有许多调用尚不清楚是否应将它们置于后台线程中。我可以谨慎行事,将所有内容都放在后台线程中。或者,为了方便起见,我可以将本地操作放在前台,除非我 运行 遇到性能问题(即状态)。我不一定喜欢后一种选择,因为如果一个操作对我来说很快,我不一定保证对其他人每次都很快。

是否有针对 libgit2 的线程指南或建议?文档似乎没有解决这个问题,而且信息有些稀疏。

更新: 具体来说,根据线程指南,我正在寻找有关在前台或后台工作任务中使用特定函数的建议的文档,而不是线程安全性。目前,我已经求助于将本地操作放在前台任务中,除非它们会产生性能问题。

Are there any sort of threading guidelines or recommendations for libgit2? It doesn't seem to be addressed by the documentation, and information is somewhat sparse.

是的,有。

Initialization

The library needs to keep track of some global state. Call

git_libgit2_init();

before calling any other libgit2 functions. You can call this function many times. A matching number of calls to

git_libgit2_shutdown(); 

will free the resources. Note that if you have worker threads, you should call git_libgit2_shutdown after those threads have exited. If you require assistance coordinating this, simply have the worker threads call git_libgit2_init at startup and git_libgit2_shutdown at shutdown.

You may safely use any libgit2 object from any thread, though there may be issues depending on the cryptographic libraries libgit2 or its dependencies link to (more on this later). For libgit2 itself, provided you take the following into consideration you won't run into issues:

Sharing objects

Use an object from a single thread at a time. Most data structures do not guard against concurrent access themselves. This is because they are rarely used in isolation and it makes more sense to synchronize access via a larger lock or similar mechanism. There are some objects which are read-only/immutable and are thus safe to share across threads, such as references and configuration snapshots.

这些准则与任何其他库或代码的准则相同。如果不是立即执行,则将其放在后台线程中并释放 UI 线程直到它完成。

git/libgit2 主要是关于 I/O(访问器除外,你可以区分它们,因为它们 return 是一个值而不是错误代码),这意味着它通常会花费未知的时间来执行任何操作。

根据上次调用 libgit2 后发生的情况,它可能需要更新它的包文件列表,或者它可能需要读取完整的打包 refs 文件,而不仅仅是一个。如果文件系统在不同的计算机上,这只会变得更糟。

由于 I/O 和世界上任何地方的文件系统,任何不是访问器的东西都可能花费无限的时间。您要在 UI 线程上调用哪些操作取决于您愿意在任何时间点对数据的位置和新鲜度做出哪些假设。