File: pth_specific.c

package info (click to toggle)
valgrind 1%3A3.6.0~svn11254%2Bnmu1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 36,460 kB
  • ctags: 39,734
  • sloc: ansic: 339,440; sh: 15,713; xml: 15,183; cpp: 6,982; asm: 6,630; perl: 5,105; makefile: 3,576; exp: 678; haskell: 250
file content (104 lines) | stat: -rw-r--r-- 1,864 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/********************************************************
 * An example source module to accompany...
 *
 * "Using POSIX Threads: Programming with Pthreads"
 *     by Brad nichols, Dick Buttlar, Jackie Farrell
 *     O'Reilly & Associates, Inc.
 *
 ********************************************************
 * specific.c
 *
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/time.h>

#include <pthread.h>

#define NUM_THREADS  3
pthread_key_t     saved_time_key;


void free_time(void *arg )
{
  struct timeval *timev=(struct timeval *)arg; 
  printf("free_time:\n");
  free(timev);
}

void save_the_time(void)
{
  struct timeval *timev;

  timev = (struct timeval *)malloc(sizeof(struct timeval));
  
  gettimeofday(timev, NULL);

  printf("save_the_time: \t\t%ld %ld\n",timev->tv_sec, timev->tv_usec);


  pthread_setspecific(saved_time_key, (void *)timev);
  
}

void what_time_did_i_save(void)
{
  struct timeval *timev;

  timev = pthread_getspecific(saved_time_key);

  printf("what_time_did_i_save: \t%ld %ld\n",timev->tv_sec, timev->tv_usec);

}  

void *thread_routine(void *arg)
{
  int *my_id=(int *)arg;

  printf("thread_routine %d\n", *my_id);

  save_the_time();

  what_time_did_i_save();
 
  return(NULL); 
}

extern int 
main(void)
{
	int       i, *id_arg;
	pthread_t threads[NUM_THREADS];

	id_arg = (int *)malloc(NUM_THREADS*sizeof(int));

	printf("main : initializing the key\n");
	pthread_key_create(&saved_time_key, free_time);

	printf("main : spawing the threads\n");
	for (i = 0; i < NUM_THREADS; i++) {

		id_arg[i] = i;

		pthread_create(&(threads[i]), 
			       NULL,
			       thread_routine,
			       (void *) &(id_arg[i]));
	}


	for (i = 0; i < NUM_THREADS; i++) {
	  pthread_join(threads[i], NULL);
 	  printf("main : thread %d has finished. \n", i);
	}

	printf("main : goodbye\n");

	return 0;
}