Is memcpy process-safe?

六月ゝ 毕业季﹏ 提交于 2019-12-29 06:19:59

问题


Ive looked online and have not been able to satisfy myself with an answer.

Is memcpy threadsafe? (in Windows)

What I mean is if I write to an area of memory shared between processes (using boost::shared_memory_object) using a single memcpy and then try read that area from another process using a single memcpy then will one process be blocked automatically while that write is happening? Where can I read about this?


回答1:


memcpy is typically coded for raw speed. It will not be thread safe. If you require this, you need to perform the memcpy call inside of a critical section or use some other semaphor mechanism.

take_mutex(&mutex);
memcpy(dst, src, count);
yield_mutex(&mutex);



回答2:


memcpy is not thread/process safe




回答3:


Routines like memcpy() (or memmove()) are part of standard C library, are included through standard <string.h> header and know nothing about any locking mechanics. Locking should be provided by some external way like inter-process mutexes, semaphores or things like this.




回答4:


You are confusing "atomic" and "thread safe". If you read and write data (with or without memcpy) concurrently in a shared region, that is not safe. But of course copying data itself is thread safe.

memcpy itself is also thread safe, at least on POSIX systems see this one, and therefore I guess it is also on Windows. Anything else would make it quite useless.

If it would be "automatically blocking", it would have to be atomic (or at least manage it's own locks) which would slow down your system. So in your case you should use your own locks.



来源:https://stackoverflow.com/questions/15145152/is-memcpy-process-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!