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 <rtl.h>
#include <time.h>
#include <pthread.h>
#define NTHREAD 5
#define THREAD_STACK_SIZE 20000
static pthread_t thread;
static char preallocated [NTHREAD][THREAD_STACK_SIZE];
static pthread_t threads [NTHREAD];
void * start_routine(void *param)
{
int arg = (int) param;
int newthread = arg - 1;
int ret;
pthread_attr_t attr;
rtl_printf("Thread %d is running\n", arg);
if (!arg) {
return 0;
}
rtl_printf("Thread %d creating thread %d\n", arg, newthread);
pthread_attr_init (&attr);
pthread_attr_setstackaddr (&attr, preallocated [newthread]);
pthread_attr_setstacksize (&attr, THREAD_STACK_SIZE);
ret = pthread_create (&threads [newthread], &attr, start_routine, (void *) (newthread));
if (ret) {
rtl_printf("failed to create thread %d\n", newthread);
}
return 0;
}
int init_module(void) {
return pthread_create (&thread, NULL, start_routine, (void *) NTHREAD);
}
void cleanup_module(void) {
int i;
pthread_cancel (thread);
pthread_join (thread, NULL);
for (i = 0; i < NTHREAD; i ++) {
if (threads[i]) {
pthread_cancel (threads[i]);
pthread_join(threads[i], NULL);
}
}
}
|