Sunday, May 20, 2007

some pthread basics

So it doesn't look like I will be able to sustain two separate blogs, one for stocks and the other for software. I am almost convinced that I should change the name to "Bits and Bulls" which should sum up the two things I am most likely to write about; software and stocks.

Well, to get me started, I was reading up on some thread basics and saw this simple and basic pthread_create implementation. Could be a good c programming interview question:

Question: What is wrong with this simple code?

/* Parameters to print_function. */
struct char_print_parms
{
/* The character to print.*/
char character;
/* The number of times to print it. */
int count;
};

/* Prints a number of characters to stderr, as given by PARAMETERS,
which is a pointer to a struct char_print_parms. */
void* char_print (void* parameters)
{
/* Cast the cookie pointer to the right type. */
struct char_print_parms* p = (struct char_print_parms*) parameters;
int i;

for (i = 0; i <>count; ++i)
fputc (p->character,stderr);
return NULL;
}

/* The main program. */
int main ()
{
pthread_t thread1_id;
pthread_t thread2_id;
struct char_print_parms thread1_args;
struct char_print_parms thread2_args;

/* Create a new thread to print 30,000 ‘x’s. */
thread1_args.character = ‘x’;
thread1_args.count = 30000;
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);

/* Create a new thread to print 20,000 o’s. */
thread2_args.character = ‘o’;
thread2_args.count = 20000;
pthread_create (&thread2_id, NULL, &char_print, &thread2_args);

return 0;
}


Answer: The main thread (which runs the main function) creates the thread parameter
structures (thread1_args and thread2_args) as local variables, and then passes pointers to these structures to the threads it creates.

So, it is very much possible that Linux will schedule the three threads in such a way that main finishes executing before either of the other two threads are done? So, if this happens, the memory containing the thread parameter structures will be deallocated while the other two threads are still accessing it.

Solution:
/* Make sure the first thread has finished. */
pthread_join (thread1_id, NULL);
/* Make sure the second thread has finished. */
pthread_join (thread2_id, NULL);

No comments: