memcpy(a, b, sizeof(a));
v.s.
a[0] = b[0];
a[1] = b[1];
...
Suppose that memcpy
should have smaller code size and high efficiency, but is there any risk to memcpy
in multi-thread system?
If the buffers are exclusive, meaning that threads are not competing for access to the data involved in the copying, then memcpy
is perfectly safe to use in multi-threaded environment. The function has no persistent state and no other side-effects besides modifying the target buffer.
Also, you can safely perform muti-threaded copying from a buffer shared by any number of threads, as long as no thread attempts to change that buffer.
But once there's a competition between the threads for writing into any shared buffers, memcpy
no longer guarantees thread safety, i.e. the operation is not atomic. Aside from what is described in 2, two simultaneous memcpy
s operating on the same buffer will interfere with each other and produce unpredictable results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With