Saturday, August 16, 2008

Thread Creation

Thread in a process is identified by a thread ID. When referring to thread IDs in C or C++ programs, use the type pthread_t. Each thread executes a thread function.

This is just an ordinary function and contains the code that the thread should run. When the function returns, the thread exits. The pthread_create function creates a new thread.

You provide it with the following:

1. A pointer to a pthread_t variable, in which the thread ID of the new thread is
stored.

2. A pointer to a thread attribute object.This object controls details of how the thread interacts with the rest of the program. If you pass NULL as the thread attribute, a thread will be created with the default thread attributes.

3. A pointer to the thread function.This is an ordinary function pointer, of this type: void* (*) (void*)

4. A thread argument value of type void*. Whatever you pass is simply passed as the argument to the thread function when the thread begins executing.


#include <pthread.h>
#include <stdio.h>


/* Prints x’s to stderr. The parameter is unused. Does not return. */

void* print_xs(void* unused)
{
while(1)
{
fputc (‘x’, stderr);
}
return NULL;
}

/* The main program. */
int main()
{
pthread_t thread_id;

/* Create a new thread. The new thread will run
the print_xs
function. */

pthread_create(&thread_id, NULL, &print_xs, NULL);

/* Print o’s continuously to stderr. */
while(1)
{
fputc(‘o’, stderr);
}

return 0;
}


Compile and link this program using the following code:

> cc -o thread-create thread-create.c -lpthread

0 comments: