Suppose I have a library with a global variable which is accessed for both Read and Write operations.

I am assuming the following:

  • A statically-linked library will not be safe-to-use concurrently on different threads.
  • A statically-linked library will be safe-to-use concurrently on different processes.
  • A dynamically-linked library will not be safe-to-use concurrently on different threads.
  • A dynamically-linked library will not be safe-to-use concurrently on different processes.

Are the assumptions above correct?

If it matters anything (although I suppose it doesn't), then I am coding in C++ and running over Windows.

Thanks

有帮助吗?

解决方案

Your last assumption is wrong, you cannot accidentally share data between libraries.

How this is achieved is specific to each library format and operating system, but the main idea is simple:

  • code is read-only: it can be shared safely (think int rand() { return 4; })
  • constants are read-only: they can be shared safely (think "Hello, World!")
  • variables are not read-only: they are not shared (an immutable "template" is shared, and used to initialize the process own copy which is private)

Even when using fork on Linux, the newly created process will not share the variables from its parent process; it will share their initial value in a copy, but both will then evolve differently.

That being said, just avoid global variables; and if possible also avoid thread-local variables.

其他提示

A dynamically-linked library will not be safe-to-use concurrently on different processes.

This is false.

Even if the library is shared among different processes, this regards the code. But each process map data to its memory space. So each process have independent global variables, even if they come from a shared library.

To be more precise, here it's been explained with good detail.

To let different processes share some memory you need to use specific libraries, as shmget() or shm_open()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top