Thread Safety in C

前端 未结 9 1967
余生分开走
余生分开走 2021-02-02 01:01

imagine I write a library in C. Further, imagine this library to be used from a multi-threaded environment. How do I make it thread-safe? More specific: How do

相关标签:
9条回答
  • 2021-02-02 01:28

    Write your own lock.

    Since you're targeting PCs you're dealing with the x86 architecture which natively supplies all the multi-threading support you should need. Go over your code and identify any functions that have shared resources. Give each shared resource a 32-bit counter. Then using the interlocked operations that are implemented by the CPUs keep track of how many threads are using each shared resource and make any thread that wants to use a shared resource wait until the resource is released.

    Here's a really good blog post about interlocked operations: Using Interlocked Instructions from C/C++

    The author focuses mostly on using the Win32 Interlocked wrappers, but pretty much every operating system has their own wrappers for the interlocked operations, and you can always write the assembly (each of these operations is only one instruction).

    0 讨论(0)
  • 2021-02-02 01:31

    Using Posix threads sounds like a good idea to me (but I'm no expert). In particular, Posix has good primitives for ensuring mutual exclusion.

    If you had to create a library without any dependencies, you would have to implement the mutual exclusion algorithms yourself, which is a bad idea.

    0 讨论(0)
  • 2021-02-02 01:31

    "imagine I write a library in C. Further, imagine this library to be used from a multi-threaded environment. How do I make it thread-safe? More specific: How do I assure, that certain functions are executed only by one thread at a time?"

    You can't -> write a thread-safe or better re-entrant functions. Unless, You would like to write system-wide locks - a very bad idea.

    "In opposite to Java or C# for example, C has no means to deal with threads/locks/etc."

    This is a joke - right? Long before the Java and C# was developed, the locks were invented and widely used as an synchronization objects...

    "I know, that operating systems support threads, but using their api would restrict the compatibility of my library very much."

    The thing is, that such libraries already exists - f.e. wxWidgets, which are offering the portable wxThread... (but this is C++)

    Anyway, there are 2 main "flavours" of C: the ANSI C and the GNU C -> two different worlds... pick one or the other.

    0 讨论(0)
提交回复
热议问题