File: test_pthread_atexit.c

package info (click to toggle)
emscripten 3.1.69%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 121,872 kB
  • sloc: ansic: 636,110; cpp: 425,974; javascript: 78,401; python: 58,404; sh: 49,154; pascal: 5,237; makefile: 3,365; asm: 2,415; lisp: 1,869
file content (43 lines) | stat: -rw-r--r-- 901 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
#include <assert.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool should_exit;

pthread_t thread;

void *workerThread(void* arg) {
  pthread_mutex_lock(&mutex);
  while (!should_exit)
    pthread_cond_wait(&cond, &mutex);
  pthread_mutex_unlock(&mutex);

  return NULL;
}

void terminateThread() {
  pthread_mutex_lock(&mutex);
  should_exit = true;
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);

  int res = 0;
  int rc = pthread_join(thread, (void**)&res);
  assert(rc == 0);
  assert(res == 0);

  printf("done waiting - thread successfully terminated\n");
}

int main(int argc, char* argv[]) {
  int rc = atexit(terminateThread);
  assert(rc == 0);

  rc = pthread_create(&thread, NULL, workerThread, NULL);
  assert(rc == 0);
  return 0;
}