#include #include #include struct thread_ret { int ret; int processed_result; }; struct thread_arg { int thread_no; int start_idx; int end_idx; }; void* thread_function(void* arg) { struct thread_arg* a = (struct thread_arg*)arg; printf("Thread %d is alive alive! Processing index's %d to %d\n", a->thread_no, a->start_idx, a->end_idx); struct thread_ret *ret = (struct thread_ret*)malloc(sizeof(*ret)); ret->ret = a->thread_no; ret->processed_result = a->start_idx * 10; return ret; } void create_thread(pthread_t* thread, int thread_no) { struct thread_arg *arg = (struct thread_arg*)malloc(sizeof(*arg)); arg->thread_no = thread_no; arg->start_idx = thread_no * 10; arg->end_idx = arg->start_idx + 10; pthread_create(thread, NULL, &thread_function, arg); } int main(void) { int err; int threads_to_spawn = 100; pthread_t thread[threads_to_spawn]; for (int i = 0; i < threads_to_spawn; i++) { create_thread(&thread[i], i); } struct thread_ret *ret[threads_to_spawn]; for (int i = 0; i < threads_to_spawn; i++) { err = pthread_join(thread[i], (void*)&ret[i]); } for (int i = 0; i < threads_to_spawn; i++) { printf("thread %d returned: %d with result %d\n", i, ret[i]->ret, ret[i]->processed_result); free(ret[i]); } return 0; }