I\'m writing a Unix application in C which uses multiple threads of control. I\'m having a problem with the main function terminating before the thread it has spawned have a
Check this simple C code I wrote for one of my libraries
/*
* Copyright (c) 2011 Dino Ciuffetti , TuxWeb S.r.l., NuvolaBase Ltd
*
* This file is part of liborient.
*
* Liborient is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Liborient is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Liborient. If not, see .
*/
#include
#include
#include
#include
//pthread_rwlock_t ptr_thr_lock = PTHREAD_RWLOCK_INITIALIZER;
typedef struct {
int t;
} thread_arguments;
void *thread_stuff(void *args) {
thread_arguments *t_args;
int tid;
t_args = (thread_arguments *)args;
//pthread_rwlock_rdlock(&ptr_thr_lock);
tid = t_args->t;
//pthread_rwlock_unlock(&ptr_thr_lock);
/*while (1) {
sleep (1);*/
printf("Thread #%i!\n", tid);
/*}*/
t_args = NULL;
pthread_exit(NULL);
return NULL;
}
int wait_threads(pthread_t threads[], thread_arguments *t_args[], int nthreads) {
int t;
int rc;
// Waiting for threads termination
for(t=0; tt = t;
//pthread_rwlock_unlock(&ptr_thr_lock);
printf("Spawning thread: %i\n", t);
rc = pthread_create(&threads[t], NULL, (void *)thread_stuff, (void *)t_args[t]);
if (rc != 0) {
printf("Error spawning thread %i: %i\n", t, rc);
wait_threads(threads, t_args, rc+1);
return t+1;
break;
}
}
return 0;
}
int main() {
pthread_t threads[20];
thread_arguments *t_args[20];
int rc;
rc = spawn_threads(threads, t_args, 20);
if (rc > 0) {
printf("Failed spawning thread number %i\n", rc-1);
return 1;
}
rc = wait_threads(threads, t_args, 20);
return 0;
}