多个线程从同一文件中读取 [英] Multiple threads reading from the same file

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

问题描述

我的平台是Windows Vista中32,用Visual C ++前preSS 2008年。

My platform is windows vista 32, with visual c++ express 2008 .

例如:

如果我有一个文件包含4000个字节,可我已经从同时文件中读取4个线程?与每个线程访问的文件中的不同部分。

if i have a file contains 4000 bytes, can i have 4 threads read from the file at same time? and each thread access a different section of the file.

主题1读0-999,线程2阅读1000年 - 2999等

thread 1 read 0-999, thread 2 read 1000 - 2999, etc.

请给C语言为例。

推荐答案

如果你不给他们写信,没必要照顾的同步/竞争状态。

If you don't write to them, no need to take care of sync / race condition.

只要打开与分享阅读不同的处理文件,一切会工作。 (即您必须打开在线程上下文的文件,而不是共享相同的文件句柄)。

Just open the file with shared reading as different handles and everything would work. (i.e., you must open the file in the thread's context instead of sharing same file handle).

#include <stdio.h>
#include <windows.h>

DWORD WINAPI mythread(LPVOID param)
{
    int i = (int) param;
    BYTE buf[1000];
    DWORD numread;

    HANDLE h = CreateFile("c:\\test.txt", GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);

    SetFilePointer(h, i * 1000, NULL, FILE_BEGIN);
    ReadFile(h, buf, sizeof(buf), &numread, NULL); 
    printf("buf[%d]: %02X %02X %02X\n", i+1, buf[0], buf[1], buf[2]);

    return 0;
}

int main()
{
    int i;
    HANDLE h[4];

    for (i = 0; i < 4; i++)
        h[i] = CreateThread(NULL, 0, mythread, (LPVOID)i, 0, NULL);

    // for (i = 0; i < 4; i++) WaitForSingleObject(h[i], INFINITE);
    WaitForMultipleObjects(4, h, TRUE, INFINITE);

    return 0;
}

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

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