从两个不同的线程读取文件 [英] Reading file from tow different thread

查看:228
本文介绍了从两个不同的线程读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从两个不同的线程中读取同一文件?我试图在每个线程中打开文件并读取其不起作用吗?
有什么想法吗?
我正在使用< windows.h>

how to read the same file from tow different threads?, i tried to open the file at each thread and read its not working?
any ideas?
I am using <windows.h>

推荐答案

如果将文件锁定在一个线程中,则第二个线程将无法打开该文件.这很可能是您的问题(基于此处提供的有限信息).
If you lock the file in one thread, then the 2nd thread will not be able to open the file. This is most likely your problem (based on the limited info provided here).


谢谢,我知道这是问题所在,问题是如何解决它?



这取决于您在当前代码中的执行方式.如果您希望两个线程独立打开并读取文件,请确保以非排他性的读取模式打开文件(这意味着它不会锁定文件以进行读取访问).

另外,您可以共享文件句柄并在两个线程中使用它,尽管这可能会带来一些副作用,您需要解决这些问题.但这是可行的.



It depends on how you are doing it in your present code. If you want the two threads to independently open and read the file, make sure you open it in a read mode that''s nonexclusive (meaning it won''t lock the file from being opened for read access).

Alternatively, you can share the file handle and use that from both threads, though that may bring in side effects that you''d then need to work around. But it''s doable.


您说过您正在使用windows.h标头;我想您的意思是您使用的是 Win32 API ,而没有 MFC ATL 或其他框架.不是吗?

Win32 打开文件的方法是使用 CreateFile功能(Windows) [ ^ ];该函数的第三个参数是dwShareMode,它告诉 Windows 是否要对该文件进行独占访问.如果为该参数指定零,则表示您拒绝其他人对该文件执行任何操作.要使其他人可以打开文件进行阅读,请使用FILE_SHARE_READ.

请参见下面的代码段:

You said that you are using the windows.h header; I suppose that you mean that you are using the Win32 API, without MFC, ATL nor other frameworks. Isn''t it?

The Win32 way to open a file is to use the CreateFile Function (Windows)[^]; the third parameter of that function is dwShareMode, which tells Windows if you want to get an exclusive access to the file or not. If you specified zero for that parameter you have denied others to do anything on the file. To give others the ability to open the file for reading you should use FILE_SHARE_READ.

See the code snippet below:

HANDLE hFile = CreateFile(
   _T("myfile.txt"),    // File name
   GENERIC_READ,        // Open for reading
   FILE_SHARE_READ,     // Allow others to read the file (but not modify it)
   NULL,                // Don't use security attributes
   OPEN_EXISTING,       // The file should already exist
   0,                   // We don't need flags and attributes
   NULL);               // Ignored while we are opening an existing file


这篇关于从两个不同的线程读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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