Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
¿Es seguro llamar a pthread_mutex_lock antes de pthread_mutex_init?

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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

El estándar POSIX dice:

Si mutex no hace referencia a un objeto mutex inicializado, el comportamiento de pthread_mutex_lock() , pthread_mutex_trylock() y pthread_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;
over 4 years ago · Santiago Trujillo Report

0

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:

  1. El mutex se desbloquea.
  2. Una condición de carrera con otro subproceso que intenta obtener el bloqueo, lo que provoca un bloqueo.
  3. Los recursos se filtraron en la biblioteca o el kernel (pero se liberarán al finalizar el proceso).
over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!