Thursday, August 5, 2010

multi-thread programming

gcc test-thread1.c -lpthread

1) test-thread1.c
Multithreading — Waiting for other threads
It is also possible to make one thread stop and wait for another thread to finish. This is accomplished with pthread_join

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

/* This is our thread function. It is like main(), but for a thread */
void *threadFunc(void *arg)
{
char *str;
int i = 0;

str=(char*)arg;

while(i < 10 )
{
usleep(1);
printf("threadFunc says: %s\n",str);
++i;
}

return NULL;
}

int main(void)
{
pthread_t pth; // this is our thread identifier
int i = 0;

/* Create worker thread */
pthread_create(&pth,NULL,threadFunc,"processing...");

/* wait for our thread to finish before continuing */
pthread_join(pth, NULL /* void ** return value could go here */);

while(i < 10 )
{
usleep(1);
printf("main() is running...\n");
++i;
}

return 0;
}




2) in test-thread2.c, if we put pthread_join after while loop
in main(). We can see alternating lines as the main() and threadFunc() threads execute and pause.

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

/* This is our thread function. It is like main(), but for a thread*/
void *threadFunc(void *arg)
{
char *str;
int i = 0;

str=(char*)arg;

while(i < 110 )
{
usleep(1);
printf("threadFunc says: %s\n",str);
++i;
}

return NULL;
}

int main(void)
{
pthread_t pth; // this is our thread identifier
int i = 0;

pthread_create(&pth,NULL,threadFunc,"foo");

while(i < 100)
{
usleep(1);
printf("main is running...\n");
++i;
}

printf("main waiting for thread to terminate...\n");
pthread_join(pth,NULL);

return 0;
}



No comments:

Post a Comment