Hi,
I am a beginner with threads in C. I need help regarding thread management in C.
my GNU thread library version is the following:
NPTL 2.9
My main program creates a thread. That thread must complete certain tasks before the program terminates. But what happens in most of the cases is that the main program ends without the thread finishing its job.
I write part of the code here.
Thanks
Code:
// main program
#include "server.h"
int main(int argc, char* argv[])
{
// Initialize the server i..e create the server thread
serverInitialize(1000);
// Task 1: in the main
// Task 2: in the main
// Now wake the server
Wake();
/**
comment: the above call wakes the server i.e.
the thread that was created in the call to serverInitialize(),
and this must run the loop in the serverFunction(),
but it does not and is terminated most of the time
*/
return 0;
}
// server.c
static rtl_pthread_t server_thread;
/** @brief Semaphore descriptor */
static rtl_sem_t wake_semaphore;
/* Prototypes */
static void serverFunction(void *t);
signed char serverInitialize( unsigned long value ){
int ret;
rtl_sem_init(&wake_semaphore, 1, 0);
ret = rtl_pthread_create( &server_thread, NULL, serverFunction, NULL );
if (ret){
ERROR_MSG("Init Fatal Error: pthread_create returned %d", ret);
return -1;
}
PRINT_MSG("Initialization OK...");
}
void Wake(void)
{
/* Activate server */
printf("\n Server to be waked now\n");
rtl_sem_post(&wake_semaphore);
return ;
}
void *serverFunction(void *t){
while (1){
/* Wait for next invocation */
rtl_sem_wait(&wake_semaphore);
// Perform task 1
// Perform task 2
// Perform task 3
....
// Perform last task
}
}
Looking forward to the comments and input