Nunca antes había tenido la oportunidad de jugar con la biblioteca pthreads, pero estoy revisando un código que involucra pthread mutexes. Revisé la documentación de pthread_mutex_lock y pthread_mutex_init , y según tengo entendido al leer las páginas man para ambas funciones, debo llamar a pthread_mutex_init antes de llamar a pthread_mutex_lock .
Sin embargo, le pregunté a un par de colegas y creen que está bien llamar a pthread_mutex_lock antes de llamar a pthread_mutex_init . El código que estoy revisando también llama a pthread_mutex_lock sin siquiera llamar a pthread_mutex_init .
Básicamente, ¿es seguro e inteligente llamar a pthread_mutex_lock antes de llamar a pthread_mutex_init (si incluso se llama a pthread_mutex_init )?
EDITAR: también veo algunos ejemplos en los que se llama a pthread_mutex_lock cuando no se usa pthread_mutex_init , comoeste ejemplo
EDIT #2: Aquí está específicamente el código que estoy revisando. Tenga en cuenta que la función de configuración adquiere y se adjunta a alguna memoria compartida que no se inicializa. Más adelante, el código Java llamará a lock() , sin que se llamen otras funciones nativas en el medio. Enlace al código
El estándar POSIX dice:
Si
mutexno hace referencia a un objeto mutex inicializado, el comportamiento depthread_mutex_lock(),pthread_mutex_trylock()ypthread_mutex_unlock()no está definido.
Por lo tanto, debe inicializar el mutex. Esto se puede hacer mediante una llamada a pthread_mutex_init() ; o, si el mutex tiene una duración de almacenamiento estático, mediante el inicializador estático PTHREAD_MUTEX_INITIALIZER . P.ej:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;Mutexes son variables que contienen estado (información) que las funciones necesitan para hacer su trabajo. Si no se necesitara información, la rutina no necesitaría una variable. Del mismo modo, la rutina no puede funcionar correctamente si le alimenta basura al azar.
La mayoría de las plataformas aceptan un objeto mutex lleno de cero bytes. Esto suele ser lo que crean pthread_mutex_init y PTHREAD_MUTEX_INITIALIZER . Da la casualidad de que el lenguaje C también garantiza que las variables globales no inicializadas se pongan a cero cuando se inicia el programa. Por lo tanto, puede parecer que no necesita inicializar los objetos pthread_mutex_t , pero este no es el caso. Las cosas que viven en la pila o en el montón, en particular, a menudo no se ponen a cero.
Llamar a pthread_mutex_init después de pthread_lock seguramente tendrá consecuencias no deseadas. Sobrescribirá la variable. Resultados potenciales:
aquí está el texto del enlace que publiqué en un comentario:
Mutual exclusion locks (mutexes) prevent multiple threads from simultaneously executing critical sections of code that access shared data (that is, mutexes are used to serialize the execution of threads). All mutexes must be global. A successful call for a mutex lock by way of mutex_lock() will cause another thread that is also trying to lock the same mutex to block until the owner thread unlocks it by way of mutex_unlock(). Threads within the same process or within other processes can share mutexes. Mutexes can synchronize threads within the **same process** or in ***other processes***. Mutexes can be used to synchronize threads between processes if the mutexes are allocated in writable memory and shared among the cooperating processes (see mmap(2)), and have been initialized for this task. Initialize Mutexes are either intra-process or inter-process, depending upon the argument passed implicitly or explicitly to the initialization of that mutex. A statically allocated mutex does not need to be explicitly initialized; by default, a statically allocated mutex is initialized with all zeros and its scope is set to be within the calling process. For inter-process synchronization, a mutex needs to be allo- cated in memory shared between these processes. Since the memory for such a mutex must be allocated dynamically, the mutex needs to be explicitly initialized using mutex_init(). also, for inter-process synchronization, besides the requirement to be allocated in shared memory, the mutexes must also use the attribute PTHREAD_PROCESS_SHARED, otherwise accessing the mutex from another process than its creator results in undefined behaviour (see this: linux.die.net/man/3/pthread_mutexattr_setpshared): The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon by any thread that has access to the memory where the mutex is allocated, even if the mutex is allocated in memory that is shared by multiple processes