Threads
The following functions are from the Linux threads library based on the POSIX 1003.b standard:
pthread_create - Adds a new thread of control to the current process.
sched_yield - Causes the current thread to yield its execution in
favor of another thread with the same or greater priority.
pthread_exit - Terminates a thread.
pthread_join - Blocks the calling thread until a specified thread
terminates.
The following program creates two threads. Each prints the name of a city a number of times, with a random delay between the prints. Run it a number of times.
#include <pthread.h>
/*
* Code of the threads
*/
void* printPlace(void* name)
{
int aux1, aux2, aux3, count;
/* Find number of loops */
if (strcmp(name, "Jamaica")==0)
count= 5;
else count=10;
/* Main loop */
for (aux1=0; aux1 < count; aux1++)
{
/* Print Name */
printf("%d %s\n", aux1, name);
/* Create a variable delay */
for (aux2= rand()/10000; aux2 > 0; aux2--)
for(aux3=10; aux3 > 0; aux3--);
/* Yields control */
/* sched_yield(); */
} pthread_exit(0);
}
void main()
{
/* Variables that keep the threads ids */
pthread_t simpleThread1, simpleThread2;
/* Maximum concurrence level */
pthread_setconcurrency(100);
printf("Concurrency %d\n", pthread_getconcurrency());
/* Create first thread */
pthread_create(&simpleThread1, 0, printPlace, "Java");
/* Create second thread */
pthread_create(&simpleThread2, 0, printPlace, "Fiji");
/* Wait until all threads stop */
pthread_join(simpleThread1, 0); pthread_join(simpleThread2, 0);
/* Wait until a specific thread stops */
/* pthread_join(simpleThread1, 0); */
}
To compile the program:
cc threads.c -o threads -lpthread
Each time you run the program it prints out a random list with the cities. Explain how it works What is the function of lines:
pthread_join(simpleThread1, 0); pthread_join(simpleThread2, 0);
Uncomment the line:
/* sched_yield(); */
Run the program. What happens? Why?
Undo the change you have done.
Change the name "Java" on the following line for "Jamaica":
pthread_create(simpleThread1, 0, printPlace,"Java");
Run the program. Now comment the lines:
pthread_join(simpleThread1, 0); pthread_join(simpleThread2, 0);
And uncomment the line:
/* pthread_join(simpleThread1, 0); */
Run the program. What happens to simpleThread1?