git/list[1] front-page[2] threads[3] people[4] search[5] about
 

static initializers

From
SZStefan Zager <szager@google.com>
Date
Jan 6, 2014, 22:02 UTC
Message-ID
<CAHOQ7J8vQ-t1knSiWQ+RKv3QvwW2DZBy29DBhkxu7tEeXoJ-CA@mail.gmail.com>
Howdy,

Is there any policy on making static initializers thread-safe? I'm working on an experimental patch to introduce threading, but I'm running into a few non-thread-safe bits like this, in convert.c:

static const char *conv_attr_name[] = {
    "crlf", "ident", "filter", "eol", "text",
};
#define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
static void convert_attrs(struct conv_attrs *ca, const char *path)
{
    int i;
    static struct git_attr_check ccheck[NUM_CONV_ATTRS];
    if (!ccheck[0].attr) {
        for (i = 0; i < NUM_CONV_ATTRS; i++)
            ccheck[i].attr = git_attr(conv_attr_name[i]);
        user_convert_tail = &user_convert;
        git_config(read_convert_config, NULL);
    }
}

The easy fix would be to stick the initialization bit into an 'extern int init_convert_config();' function, and invoke it prior to the threaded part of my code. That would be no worse than the current state of affairs, which is to say that adding threading is rife with hidden perils.

A more comprehensive fix might be:
#include <pthread.h>
static pthread_mutex_t convert_config_mutex = PTHREAD_MUTEX_INITIALIZER;
static void convert_attrs(struct conv_attrs *ca, const char *path)
{
    int i;
    static struct git_attr_check ccheck[NUM_CONV_ATTRS];
    pthread_mutex_lock(&convert_config_mutex);
    if (!ccheck[0].attr) {
        for (i = 0; i < NUM_CONV_ATTRS; i++)
            ccheck[i].attr = git_attr(conv_attr_name[i]);
        user_convert_tail = &user_convert;
        git_config(read_convert_config, NULL);
    }
    pthread_mutex_unlock(&convert_config_mutex);
}

Unfortunately, I don't think mingw/msys supports PTHREAD_MUTEX_INITIALIZER. A possible workaround would be:

static pthread_mutex_t convert_config_mutex;
static void init_convert_config_mutex() __attribute__((constructor));
static void init_convert_config_mutex()
{
    pthread_mutex_init(&convert_config_mutex);
}
But then, I'm not whether mingw/msys supports __attribute__(constructor).

Can anyone give me some guidance before I go to much further into the weeds (and I'm neck-deep as it is)?

Thanks,
Stefan
Next: Erik Faye-Lund
Message 1 of 2 in “static initializers”
  1. Stefan ZagerJan 6, 2014
  2. Erik Faye-LundJan 7, 2014

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.