1 /* Copyright (c) 2002-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 /* Code with both recursive and non-recursive mutexes */
12 // Structure to hold the mutex's name and pointer to the actual mutex
15 pthread_mutex_t* mutex;
18 static void* thread_function(void* arg)
20 ThreadData* data = (ThreadData*)arg;
21 pthread_mutex_t* mutex = data->mutex;
22 const char* name = data->name;
24 pthread_mutex_lock(mutex);
25 fprintf(stderr, "Got the lock on the %s mutex.\n", name);
27 // Attempt to relock the mutex - This behavior depends on the mutex type
28 if (pthread_mutex_trylock(mutex) == 0) {
29 fprintf(stderr, "Got the lock again on the %s mutex.\n", name);
30 pthread_mutex_unlock(mutex);
32 fprintf(stderr, "Failed to relock the %s mutex.\n", name);
35 pthread_mutex_unlock(mutex);
37 // pthread_exit(NULL); TODO: segfaulting
43 pthread_t thread1, thread2;
44 pthread_mutex_t mutex_dflt = PTHREAD_MUTEX_INITIALIZER; // Non-recursive mutex
46 pthread_mutexattr_t attr;
47 pthread_mutexattr_init(&attr);
48 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
49 pthread_mutex_t mutex_rec;
50 pthread_mutex_init(&mutex_rec, &attr);
52 ThreadData data1 = {"default", &mutex_dflt};
53 ThreadData data2 = {"recursive", &mutex_rec};
55 pthread_create(&thread1, NULL, thread_function, &data1);
56 pthread_create(&thread2, NULL, thread_function, &data2);
58 pthread_join(thread1, NULL);
59 pthread_join(thread2, NULL);
61 pthread_mutex_destroy(&mutex_dflt);
62 pthread_mutex_destroy(&mutex_rec);