File: pthread2.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 (74 lines) | stat: -rw-r--r-- 1,704 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// _GNU_SOURCE for syscall
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>

#define THREAD_CNT 5

int numWorkers = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

static void *threadMain (void *_n);

static int maxWorkers = THREAD_CNT;

int main (int argc, char* argv[])
{
  int count = 0;
  if (argc > 1) {
    int c = atoi(argv[1]);
    if (c > 1) {
      maxWorkers = c;
    }
  }

  while (1) {
    pthread_mutex_lock(&mutex);
    if (numWorkers < maxWorkers+1) {
      pthread_t pthread_id;
      pthread_attr_t attr;
      pthread_attr_init(&attr);
      pthread_attr_setstacksize(&attr, 1024 * 1024);
      pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
      int *id = malloc(sizeof(int));
      *id = count++;

      int res = pthread_create(&pthread_id, &attr, &threadMain, id);
      if (res != 0) {
        fprintf(stderr, "error creating thread: %s\n", strerror(res));
        return (-1);
      } else {
        numWorkers++;
      }
    }
    pthread_mutex_unlock(&mutex);
  }
  return (0);
}

static void *threadMain (void *data)
{
  int id = *(int*) data;

  while (1) {
    printf("Worker: %d (%ld) alive. numWorkers: %d\n",
           id, (long)syscall(SYS_gettid), numWorkers);
    // usleep(100*1000);
    pthread_mutex_lock(&mutex);
    if (numWorkers > maxWorkers) {
      numWorkers--;
      printf("Worker: %d (%ld) exiting: numWorkers: %d\n",
             id, (long)syscall(SYS_gettid), numWorkers);
      pthread_mutex_unlock(&mutex);
      free(data);
      pthread_exit(NULL);
    }
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}