Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / examples / sthread / pthread-mutex-recursive.c
1 /* Copyright (c) 2002-2023. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 /* Code with both recursive and non-recursive mutexes */
7
8 #include <pthread.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 // Structure to hold the mutex's name and pointer to the actual mutex
13 typedef struct {
14   const char* name;
15   pthread_mutex_t* mutex;
16 } ThreadData;
17
18 static void* thread_function(void* arg)
19 {
20   ThreadData* data       = (ThreadData*)arg;
21   pthread_mutex_t* mutex = data->mutex;
22   const char* name       = data->name;
23
24   pthread_mutex_lock(mutex);
25   fprintf(stderr, "Got the lock on the %s mutex.\n", name);
26
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);
31   } else {
32     fprintf(stderr, "Failed to relock the %s mutex.\n", name);
33   }
34
35   pthread_mutex_unlock(mutex);
36
37   // pthread_exit(NULL); TODO: segfaulting
38   return NULL;
39 }
40
41 int main()
42 {
43   pthread_t thread1;
44   pthread_t thread2;
45   pthread_mutex_t mutex_dflt = PTHREAD_MUTEX_INITIALIZER; // Non-recursive mutex
46
47   pthread_mutexattr_t attr;
48   pthread_mutexattr_init(&attr);
49   pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
50   pthread_mutex_t mutex_rec;
51   pthread_mutex_init(&mutex_rec, &attr);
52
53   ThreadData data1 = {"default", &mutex_dflt};
54   ThreadData data2 = {"recursive", &mutex_rec};
55
56   pthread_create(&thread1, NULL, thread_function, &data1);
57   pthread_create(&thread2, NULL, thread_function, &data2);
58
59   pthread_join(thread1, NULL);
60   pthread_join(thread2, NULL);
61
62   pthread_mutex_destroy(&mutex_dflt);
63   pthread_mutex_destroy(&mutex_rec);
64
65   return 0;
66 }