File: mutex4.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 (60 lines) | stat: -rw-r--r-- 1,648 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
53
54
55
56
57
58
59
60
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include "dmtcp.h"

// This code uses the attribute PTHREAD_MUTEX_ERRORCHECK.
// An error-checking mutex must check the owner when unlocking.
// (In contrast, a recursive mutex will check the owner when locking.)
// This version runs with two threads instead of just one thread.

pthread_mutex_t mutex;
void *mutex_loop(void *arg);

int main() {
  pthread_mutexattr_t attr;
  pthread_mutexattr_init(&attr);
  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
  pthread_mutex_init(&mutex, &attr);

  pthread_t thread1, thread2;
  pthread_create(&thread1, NULL, mutex_loop, NULL);
  pthread_create(&thread2, NULL, mutex_loop, NULL);
  // This will block forever.  mutex_loop() doesn't return.
  pthread_join(thread1, NULL);
  pthread_join(thread2, NULL);
  return 0;
}

void *mutex_loop(void *arg /* NOTUSED */) {
  int counter = 0;

  struct timespec hundredth_second;
  hundredth_second.tv_sec = 0;
  hundredth_second.tv_nsec = 10000000; /* 10,000,000 */

  while (1) {
    int rc;
    rc = pthread_mutex_lock(&mutex);
    if (rc != 0) {
      printf("pthread_mutex_lock (error-checking): %s\n\n",
             strerror(rc));
      exit(1);
    }
    // Wait a little to optimize chances of checkpoint occurring here.
    nanosleep(&hundredth_second, NULL);
    if (counter++ % 50 == 0) {
      printf("b"); fflush(stdout);
    }
    rc = pthread_mutex_unlock(&mutex);
    if (rc != 0) {
      printf("pthread_mutex_unlock (error-checking): %s\n\n",
             strerror(rc));
      exit(1);
    }
  }
  return NULL;
}