简体   繁体   中英

Making a C library thread safe

I am writing a shared library in C. I know C functions are not thread safe.

My library routines looks like,

struct lib_handle {
....
};

int lib_init(lib_handle **handle);
int lib_process(lib_handle *handle);
....
....

Every method takes a pointer to lib_handle object. All the state is stored inside this structure. No global variables are used.

I assume if each thread creates it's own lib_handle instances, multiple threads can use the library functions. Since each thread has it's own handle, everythibg should work.

I haven't validated this assumption yet. I am wondering what you guys think about this design and do you thing I can state my library as thread safe given each thread has it's own handles?

Any help would be great!

That will make data/state of library thread safe.

But you also have to make sure that your library uses threadsafe functions from other libraries, eg use strtok_r instead of strtok .

Threads works in shared memory space. Unsafe objects are the objects which can be accessed by multiple threads simulteniously. So if you have single lib_handle object for each threads there will be no problems.

If each thread has a private lib_handle object your library should be fully threadsafe; if you let several threads share lib_handle objects the person using your library can still makea thread safe program if she uses your library correctly (ie your library is not inherently thread-unsafe which it would be if you used eg global variables).

If this mode of operation (shared lib_handle) is interesting you should clearly separate the functions which only read the state of lib_handle and those which manipulate the state of lib_handle. The former needing a read lock and the latter needing a write lock (the calling scope must handle this).

For what it is worth I have used the pattern you describe quite a lot, and like it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM