为什么.net代码版本挂起,而c++没有
本文关键字:c++ 没有 挂起 net 代码 版本 为什么 | 更新日期: 2023-09-27 17:49:23
为什么相同的代码在。net (c#)挂起,但在c++中不是?真正的问题在System.IO中。文件流,但我把它减少到CreateFile,尽管如此,它仍然挂在。net中(虽然几乎100%类似于c++代码):
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static IntPtr _handle;
static void Main()
{
_handle = CreateFile("test.txt", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
new Thread(MyProc) { IsBackground = true }.Start();
new Thread(MyProc) { IsBackground = true }.Start();
Console.ReadKey();
}
static void MyProc()
{
for (int i = 0; i < int.MaxValue; i++)
{
Console.WriteLine(i);
var _overlapped = new NativeOverlapped();
LockFileEx(_handle, LOCKFILE_EXCLUSIVE_LOCK, 0, int.MaxValue, int.MaxValue, ref _overlapped);
Thread.Sleep(50);
UnlockFileEx(_handle, 0, int.MaxValue, int.MaxValue, ref _overlapped);
}
}
public const int LOCKFILE_EXCLUSIVE_LOCK = 0x00000002;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LockFileEx(IntPtr hFile, int flags, int reserved, int numberOfBytesToLockLow, int numberOfBytesToLockHigh,
ref NativeOverlapped overlapped);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UnlockFileEx(IntPtr hFile, int reserved, int numberOfBytesToUnlockLow, int numberOfBytesToUnlockHigh,
ref NativeOverlapped overlapped);
public const int GENERIC_READ = unchecked((int)0x80000000L);
public const int GENERIC_WRITE = (int)0x40000000L;
public const int OPEN_ALWAYS = 4;
public const int FILE_SHARE_READ = 0x00000001;
public const int FILE_SHARE_WRITE = 0x00000002;
public const int FILE_SHARE_DELETE = 0x00000004;
public const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateFile(string fileName, int desiredAccess, int shareMode,
IntPtr pSecurityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr hTemplateFile);
}
}
下面是不挂起的c++版本
#include "stdafx.h"
#include <thread>
#include <Windows.h>
HANDLE hFile;
DWORD WINAPI MyProc(LPVOID lpParam);
int _tmain(int argc, _TCHAR* argv[])
{
hFile = CreateFile(L"test.txt", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
HANDLE hThread1 = CreateThread(NULL, 0, MyProc, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, MyProc, NULL, 0, NULL);
int ch = getchar();
return 0;
}
DWORD WINAPI MyProc(LPVOID lpParam)
{
for(int i = 0; i < INT_MAX; i++)
{
printf("%d'r'n", i);
OVERLAPPED overlapped = {0};
LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, INT_MAX, INT_MAX, &overlapped);
Sleep(50);
UnlockFileEx(hFile, 0, INT_MAX, INT_MAX, &overlapped);
}
return 0;
}
看起来在同一个文件句柄上两次调用LOCKFILE_EXCLUSIVE_LOCK是无效的。它必须是不同的文件句柄,或者该句柄的某种进程内同步。
令人不安的是,在MSDN文档中没有明确的问题。并且在运行时没有明确的错误信息。而且,在我看来,这个问题似乎只在我的电脑上出现。