File: dmtcp3.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 (56 lines) | stat: -rw-r--r-- 1,095 bytes parent folder | download | duplicates (3)
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
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void *threadMain(void *dummy);

#define N 10

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int numWaiting = 0;

int main ()
{
  int x[N], i;
  pthread_t t[N];
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstacksize(&attr, 1024 * 1024);

  for (i = 0; i < N-1; i ++) {
    x[i]=i;
    if (pthread_create (&t[i], &attr, &threadMain, x+i) < 0) {
      fprintf (stderr, "error creating thread: %s\n", strerror (errno));
      return (-1);
    }
  }
  x[N-1]=N-1;
  threadMain(x+N-1);
  return (0);
}

static void *threadMain (void *_n)
{
  int* n = (int*) _n;
  int count = 0;

  while (1) {
    pthread_mutex_lock(&mutex);
    if(numWaiting > N/2)
      pthread_cond_signal(&cond);

    numWaiting++;
    pthread_cond_wait(&cond, &mutex);
    numWaiting--;
    pthread_mutex_unlock(&mutex);

    if(count++ % 1000 == 0)
      printf("thread%3d: %8d\n", *n, count/1000);
  }

  return (NULL);
}