Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 745
Navaneeth K N Avatar asked Aug 17 '12 05:08

Navaneeth K N


2 Answers

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, e.g. use strtok_r instead of strtok.

like image 59
Rohan Avatar answered Oct 09 '22 23:10

Rohan


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.

like image 45
Danil Onishchenko Avatar answered Oct 09 '22 23:10

Danil Onishchenko