File: pthread5.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 (48 lines) | stat: -rw-r--r-- 1,253 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
/* Compile with:  gcc THIS_FILE -lpthread */

// _GNU_SOURCE required for MAP_ANONYMOUS
#define _GNU_SOURCE
// pthread_attr_setstack() needs _POSIX_C_SOURCE >= 200112L
#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#include <sys/mman.h>

void *start_routine(void*);

int main() {
  pthread_t thread;
  void *arg;
  size_t stacksize = 1024 * 1024;
  void *stackaddr = mmap(0, stacksize, PROT_READ|PROT_WRITE,
                         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  assert(stackaddr != MAP_FAILED);
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstack(&attr, stackaddr, stacksize);

  while (1) {
    arg = malloc(10);
    int res = pthread_create(&thread, &attr, start_routine, arg);
    if (res != 0) {
      fprintf(stderr, "error creating thread: %s\n", strerror(res));
      return -1;
    }
    /* thread will free arg, and pass back to us a different arg */
    res = pthread_join(thread, &arg);
    if (res != 0) {
      fprintf(stderr, "pthread_join() failed: %s\n", strerror(res));
      return -1;
    }
    free(arg);
  }
}

void *start_routine(void* arg) {
  free(arg);
  void *valuePtr = malloc(20);
  pthread_exit(valuePtr);
}