File: pthread-mutex-recursive.c

package info (click to toggle)
simgrid 4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 39,192 kB
  • sloc: cpp: 124,913; ansic: 66,744; python: 8,560; java: 6,773; fortran: 6,079; f90: 5,123; xml: 4,587; sh: 2,194; perl: 1,436; makefile: 111; lisp: 49; javascript: 7; sed: 6
file content (66 lines) | stat: -rw-r--r-- 1,848 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* Copyright (c) 2002-2025. The SimGrid Team. All rights reserved.          */

/* This program is free software; you can redistribute it and/or modify it
 * under the terms of the license (GNU LGPL) which comes with this package. */

/* Code with both recursive and non-recursive mutexes */

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

// Structure to hold the mutex's name and pointer to the actual mutex
typedef struct {
  const char* name;
  pthread_mutex_t* mutex;
} ThreadData;

static void* thread_function(void* arg)
{
  ThreadData* data       = (ThreadData*)arg;
  pthread_mutex_t* mutex = data->mutex;
  const char* name       = data->name;

  pthread_mutex_lock(mutex);
  fprintf(stderr, "Got the lock on the %s mutex.\n", name);

  // Attempt to relock the mutex - This behavior depends on the mutex type
  if (pthread_mutex_trylock(mutex) == 0) {
    fprintf(stderr, "Got the lock again on the %s mutex.\n", name);
    pthread_mutex_unlock(mutex);
  } else {
    fprintf(stderr, "Failed to relock the %s mutex.\n", name);
  }

  pthread_mutex_unlock(mutex);

  // pthread_exit(NULL); TODO: segfaulting
  return NULL;
}

int main()
{
  pthread_t thread1;
  pthread_t thread2;
  pthread_mutex_t mutex_dflt = PTHREAD_MUTEX_INITIALIZER; // Non-recursive mutex

  pthread_mutexattr_t attr;
  pthread_mutexattr_init(&attr);
  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  pthread_mutex_t mutex_rec;
  pthread_mutex_init(&mutex_rec, &attr);

  ThreadData data1 = {"default", &mutex_dflt};
  ThreadData data2 = {"recursive", &mutex_rec};

  pthread_create(&thread1, NULL, thread_function, &data1);
  pthread_create(&thread2, NULL, thread_function, &data2);

  pthread_join(thread1, NULL);
  pthread_join(thread2, NULL);

  pthread_mutex_destroy(&mutex_dflt);
  pthread_mutex_destroy(&mutex_rec);

  return 0;
}