Using thread-safe libraries
<p>I can think of two ways a thread-safe library can be used: </p>

<p>One is having a global instance of the library protected by a mutex, which is initialised by the main thread and used by worker threads, like so:</p>

<pre><code>mutex g_lib_mutex;
lib_t g_lib;

thread:
    lock(&amp;g_lib_mutex);
    /* use lib */
    unlock(&amp;g_lib_mutex);


main:
    lib_init(&amp;g_lib);
    start_threads(thread);

    lock(&amp;g_lib_mutex);
    /* use lib */
    unlock(&amp;g_lib_mutex);

    join_threads();
    lib_close(&amp;g_lib);
</code></pre>

<p>The other, is for every thread to have a local instance of the library, something like this: </p>

<pre><code>thread:
    lib_t g_lib;
    lib_init(&amp;g_lib);
    /* use lib */
    lib_close(&amp;g_lib);


main:
    start_threads(thread);
    lib_t g_lib;
    lib_init(&amp;g_lib);
    /* use lib */
    lib_close(&amp;g_lib);
</code></pre>

<p>Which of these ways is more correct / preferable?</p>

<p>Do I need to protect library calls with a global mutex in both cases? </p>

<p>I was trying to use libmysql and POSIX message queues in a multi-threaded application when this question crossed my mind. </p>