c++ - _fread_nolock、_fseek_nolock 的预期用途是什么?

标签 c++ windows multithreading fread fseek

我们有一个 C++ 类,它基本上从二进制文件读取和写入 vector 。将单个 vector 加载到内存中的示例性读取函数如下所示:

int load (const __int64 index, T* values) const {

 int re = _fseeki64(_file, index * _vectorSize + _offsetData, SEEK_SET); 
 assert(re == 0);

 size_t read = fread(values, sizeof(T), _vectorElements, _file);
 assert(read == _vectorElements);

 return 0;}

Out 程序是多线程的,带有 OpenMP,多个线程同时访问同一个文件。为避免多线程问题,我们始终在 OpenMP 关键语句中包含函数调用:

#pragma omp critical {
    load(...);
}

我知道 Microsoft Visual C++ 运行时包含几个函数,如 _fseek_nolock_fread_nolock_fwrite_nolock 等等...例如_fread_nolock()函数描述为

This function is a non-locking version of fread. It is identical to fread except that it is not protected from interference by other threads. It might be faster because it does not incur the overhead of locking out other threads. Use this function only in thread-safe contexts such as single-threaded applications or where the calling scope already handles thread isolation.

现在我的问题是:我知道该函数会阻止“重入”调用,因此在其他线程返回之前没有其他线程会进入该函数。但是,我不明白为什么有必要以这种方式保护单个功能。恕我直言,访问/修改文件指针(代码示例中的 _file)的所有函数都必须受到保护,因此必须是线程安全的。这需要围绕实际调用标准 C 函数 fseek 和 fread 的整个函数 block 建立一个锁,所以我看不出提供此类非阻塞函数的意义。

谁能向我解释这些锁定机制,因为我认为我们偏执的锁定方案会浪费一些性能?

提前致谢!

最佳答案

对于一些简单的代码,FILE * 中的锁就足够了。考虑一个基本的日志记录基础架构,您希望所有线程都通过一个通用的 FILE *.log 进行记录。内部锁将确保 FILE * 不会被多个线程破坏,并且由于每个日志行都应该独立,因此个人调用交错的方式无关紧要。

关于c++ - _fread_nolock、_fseek_nolock 的预期用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1890448/

相关文章:

windows - 在 Windows 10 bash shell 中使用 conemu 时,为什么 UP 键不显示上一个命令?

python - 如何使用 pyinstaller 将包转换为 exe?

java - 重新启动 java 线程

java - ReentrantLock的trylock方法不允许多个线程轮流

c++11 - 使用 {} 构造函数直接从 char* 初始化 std::string

c++ - 有没有办法将 Fitnesse 合并到 C++ 代码中?

c++ - 如何在C++中打开和修改png

windows - Jenkins 无法连接到存储库 : Command returned status code 128:

java - 可以停止使用 httpConnection.connect() 连接到 URL 的线程吗?

c++ - 设置 void * 指针等于一个整数