NOAA-EMC / NCEPLIBS-g2c

This library contains C decoder/encoder routines for GRIB edition 2.
Other
18 stars 11 forks source link

Making library threadsafe with pthreads library #366

Closed edwardhartnett closed 1 year ago

edwardhartnett commented 1 year ago

Part of #365

In this PR I add an option to CMake to use pthreads, off by default.

If it is used, pthread is included in the build, a POSIX threading library. Using pthread the library is made threadsafe.

This is (minimally) tested in tst_files.c. More testing is coming after this PR is merged.

AlexanderRichert-NOAA commented 1 year ago

Outside of the test that uses two threads, is it correct to say that the addition of pthreads provides thread safety but is not intended to add parallelism? Of what I can understand so far these changes make sense (still getting acquainted with pthreads).

edwardhartnett commented 1 year ago

@AlexanderRichert-NOAA you are correct. Other than in testing, the only thing we have to worry about with threads is to protect the critical sections of code with a mutex.

In practice, this means we put:

MUTEX_LOCK(m); at the beginning of top-level functions like g2c_open(), and MUTEX_UNLOCK(m) at the bottom...

But in tests, we need to actually launch some threads to test. ;-) So the code there is more complex. I'm hoping/planning to smooth this out and come up with an idiom which is compact and simple, and allows tests to be written for sequential execution, but also allows them to be run as threads in a threaded build.

edwardhartnett commented 1 year ago

@Hang-Lei-NOAA please review and approve...