1
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t *mutexes;

void *thread_work(void *id)
{
    long tid = (long)id;

    while(some_condition)
    {
        pthread_mutex_lock(mutexes[0]);
    }
}

If I allocate memory for mutexes dynamically in the main function, is it thread safe to use mutexes[0] in threads? Are they going refer to the same mutexes or maybe create a copy for each thread?

I know it's basic knowledge but I got confused after reading some tutorials.

pmichna
  • 4,800
  • 13
  • 53
  • 90
  • 1
    The threads will be accessing the same mutexes. Heap memory is shared between threads. This answer is quite good http://stackoverflow.com/questions/1665419/do-threads-have-a-distinct-heap/1665432#1665432 – Baldrick Nov 15 '13 at 10:07
  • It will be shared, but should be made thread safe. https://computing.llnl.gov/tutorials/pthreads/#PassingArguments – Phil_12d3 Nov 15 '13 at 10:13
  • @Phil_12d3 That doesn't answer my question, I think. I don't want to pass the mutexes as parameters. I want them to be global variables and just refer to them in the threads. The index of a mutex would be chosen according to some conditions. – pmichna Nov 15 '13 at 10:16
  • Does this help more. http://stackoverflow.com/questions/7382636/accessing-global-variables-in-pthreads-in-different-c-files – Phil_12d3 Nov 15 '13 at 10:29
  • The interesting thing about this question is: Does one needs to protect the concurrent access to `pthread_mutex_t * mutexes` using another mutex? – alk Nov 15 '13 at 14:45

1 Answers1

2

Heap memory is shared between threads, which in case of mutexes is vital.

If you want to synchronize two threads using a mutex, they must call pthread_mutex_lock on the same mutex object.

Conceptually, a mutex is a shared resource, while a lock is thread-specific: At most one thread can have a lock at the same time and locks are not shared between threads. The underlying mutex on the other side is shared: All threads use the same mutex to determine whether it is safe to obtain a lock.

Note that in posix, locks are not represented by actual objects but are implicit in the program state. But I still find this a useful way to think about those things.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166