Context:
I am working on an application that needs fast access to large files, so I use memory-mapping. Reading and writing becomes a simple memcpy
in consequence. I am now trying to add the ability to abort any reads or writes in progress.
The first thing that came to mind (since I don't know about any interruptable memcpy function) was to periodically memcpy
a few KB and check if the operation should be aborted. This should ensure a near-instantanious abortion, if the read is reasonably fast.
If it isn't however the application shouldn't take ages to abort, so my second idea was using multithreading. The memcpy happens in its own thread, and a controlling thread uses WaitForMultipleObjects
on an event that signals abortion, and the memcpy-thread. It would then kill the memcpy-thread, if the abortion-event was signaled. However, the documentation on TerminateThread states that one should be absolutely sure that one does not leave the system in a bad state by not releasing ressource for instance.
Question:
Does a memcpy do anything that would make it unsafe to kill it when copying mapped memory? Is it safe to do so? Is it implementation dependant (using different operating systems/architectures than Windows x86-64)?
I do realize that using the second approach may be complete overkill, since no 1KB read/write is every going to take that long realistically, but I just want to be safe.
If at all possible you should choose a different design, TerminateThread
should not be thought of as a normal function, it is more for debugging/power tools.
I would recommend that you create a wrapper around memcpy
that copies in chunks. The chunk size is really up to you, depends on your responsiveness requirements. 1 MiB is probably a good starting point.
If you absolutely want to kill threads you have to take a couple of things into account:
memcpy
works internally nor how much it copied so you have to assume that the whole range is undefined when you abort.