File: mutex2.c

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (52 lines) | stat: -rw-r--r-- 1,441 bytes parent folder | download
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
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include "dmtcp.h"

// WE CAN ALTERNATELY USE trylock, and timedlock with a timeout of zerotime.
// They do the same thing, and we can test both methods in the same code.
// But it's better to make them separate tests, so that we always
// // fail if just one of them causes a problem.

int main() {
  int counter = 0;
  struct timespec zerotime;
  zerotime.tv_sec = 0;
  zerotime.tv_nsec = 0;

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

  dmtcp_disable_ckpt();
  while (1) {
    int rc;
    rc = pthread_mutex_timedlock(&mutex, &zerotime);
    if (rc != 0) {
      printf("pthread_mutex_timedlock: %s\n\n",
             strerror(rc));
      exit(1);
    }
    dmtcp_enable_ckpt();
    if (counter++ % 1000000 == 0) {
      printf("b"); fflush(stdout);
    }
    dmtcp_disable_ckpt();
    // zerotime means either succeed in locking or fail immediately.
    rc = pthread_mutex_timedlock(&mutex, &zerotime);
    if (rc != 0) {
      printf("pthread_mutex_timedlock (recursive): %s\n\n",
             strerror(rc));
      exit(1);
    }
    rc = pthread_mutex_unlock(&mutex);
    rc = pthread_mutex_unlock(&mutex);
    if (rc == -1) perror("pthread_mutex_unlock");
  }
  return 0;
}