| 1 |
#include <stdio.h> |
| 2 |
#include <stdlib.h> |
| 3 |
#include <pthread.h> |
| 4 |
#include <sys/types.h> |
| 5 |
#include <sys/stat.h> |
| 6 |
#include <fcntl.h> |
| 7 |
#include <unistd.h> |
| 8 |
|
| 9 |
void *thread_function( void *ptr ); |
| 10 |
|
| 11 |
struct thread_data { |
| 12 |
int tnum; |
| 13 |
}; |
| 14 |
|
| 15 |
int |
| 16 |
main() |
| 17 |
{ |
| 18 |
pthread_t thread1, thread2; |
| 19 |
int iret1, iret2; |
| 20 |
|
| 21 |
/* Create independent threads each of which will execute function */ |
| 22 |
struct thread_data t1 = { 1 }; |
| 23 |
struct thread_data t2 = { 2 }; |
| 24 |
iret1 = pthread_create(&thread1, NULL, thread_function, (void*) &t1); |
| 25 |
iret2 = pthread_create(&thread2, NULL, thread_function, (void*) &t2); |
| 26 |
|
| 27 |
/* Wait till threads are complete before main continues. Unless we |
| 28 |
* wait we run the risk of executing an exit which will terminate |
| 29 |
* the process and all threads before the threads have |
| 30 |
* completed. */ |
| 31 |
pthread_join(thread1, NULL); |
| 32 |
pthread_join(thread2, NULL); |
| 33 |
|
| 34 |
exit(0); |
| 35 |
} |
| 36 |
|
| 37 |
void *thread_function(void *ptr) |
| 38 |
{ |
| 39 |
struct thread_data *td = ptr; |
| 40 |
if (td->tnum == 1) { |
| 41 |
int fd = open("/dev/null", O_RDONLY); |
| 42 |
close(fd); |
| 43 |
} |
| 44 |
} |