Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any multi-thread concern on memcpy function?

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?

like image 312
Tmx Avatar asked Oct 18 '25 11:10

Tmx


1 Answers

  1. 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.

  2. 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.

  3. 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 memcpys operating on the same buffer will interfere with each other and produce unpredictable results.

like image 139
AnT Avatar answered Oct 20 '25 01:10

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!