-2

I'm curious to know if a thread running memcpy gets preempted by other threads while memcpy is in progress?.

If yes, what would happen to the copy in progress?. How's it handled internally?.

srccode
  • 721
  • 4
  • 16
  • 6
    Yes it can get preempted (assuming it's not running on a non-preemptible thread or high priority thread). But `memcpy` is not special in any way. The same thing happens no matter what is running when the preemption occurs. The kernel will save the thread state and restore the state of some other thread/process (ie, context switch). – kaylum Feb 07 '21 at 10:36
  • 4
    This has the aroma of an [XY problem](https://en.wikipedia.org/wiki/XY_problem). There is nothing in the standard(s? pick a language) that dictates `memcpy` will be non-preemptable regardless. – WhozCraig Feb 07 '21 at 10:36
  • If that memory area is used only by the thread running `memcpy`, the preemption is transparent to it. If it instead is shared, protect read/write with a mutex. – Roberto Caboni Feb 07 '21 at 10:50

1 Answers1

0

As with nearly every function in the C++ standard library, memcpy is not defined in terms of what its state might be after it has been called, but before it has returned.

Any attempt by a thread to access data that memcpy is in the process of writing to is, by definition, a race condition.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180