'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?



Solution 1:[1]

  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.

Solution 2:[2]

If you do not use lock to ensure exclusive, using memcpy() only will be very dangerous! The memcpy() is only responsible for copying memory, don't ensure thread safe, you should add lock by yourself. In C language, in user's space, you can use mutex for ensuring exclusive.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 cwfighter