File: pthread4.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 (52 lines) | stat: -rw-r--r-- 1,279 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
#include <stdio.h>
#include <sched.h>
#include <unistd.h>
#include <pthread.h>

#define NUM_THREADS 4
#define NUM_THREADS_2 1000 * 1000

pthread_t child_thread_id[NUM_THREADS];
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;

int counter = 0;

void * child_thread_2(void *arg)
{
    pthread_mutex_lock(&count_mutex);
    counter++;
    pthread_mutex_unlock(&count_mutex);
    return NULL;
}

void * child_thread(void *arg)
{
    int i;
    printf("Child thread...\n");
    for(i = 0; i < NUM_THREADS_2; i++) {
        pthread_t my_child;
        pthread_create(&my_child, NULL, child_thread_2, NULL);
        printf("b"); fflush(stdout);
        pthread_join(my_child, NULL);
    }
    printf("\nThread increment completed\n");
    return NULL;
}

int main(int argc, char *argv[]) {
    int i;
    printf("\nCreating threads...\n");
    for(i = 0; i < NUM_THREADS; i++) {
        pthread_create(&child_thread_id[i], NULL, child_thread, NULL);
    }
    printf("\nJoining threads...\n");
    for(i = 0; i < NUM_THREADS; i++) {
      int ret = pthread_join(child_thread_id[i], NULL);
      if (ret != 0) {
        printf("\n\n pthread_join returned an error :%d\n", ret);
      }
    }
    printf("\nEnd counter value: %d\n", counter);
    fflush(stdout);
    return 0;
}