0% found this document useful (0 votes)
15 views6 pages

Lab Manual 09

The document provides an overview of threads in operating systems, defining a thread as a lightweight process that shares resources with other threads but maintains its own program counter and stack. It discusses the advantages of multithreading, such as faster creation and context switching, and outlines how to implement multithreading in C using POSIX Threads (Pthreads). Additionally, it includes examples of C programs demonstrating thread creation and management, along with an assignment for creating multiple threads that interact with global and static variables.

Uploaded by

Zayn Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Lab Manual 09

The document provides an overview of threads in operating systems, defining a thread as a lightweight process that shares resources with other threads but maintains its own program counter and stack. It discusses the advantages of multithreading, such as faster creation and context switching, and outlines how to implement multithreading in C using POSIX Threads (Pthreads). Additionally, it includes examples of C programs demonstrating thread creation and management, along with an assignment for creating multiple threads that interact with global and static variables.

Uploaded by

Zayn Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Operating Systems CSC322

Lab Manual
Topic: Threads
What is a thread:
A thread is a single sequence stream within in a process. Because threads have some of the
properties of processes, they are sometimes called lightweight processes.

What are the differences between process and thread?

Threads are not independent of one other like processes as a result threads shares with other threads
their code section, data section and OS resources like open files and signals. But, like process, a
thread has its own program counter (PC), a register set, and a stack space.

Why Multithreading?
Threads are popular way to improve application through parallelism. For example, in a browser,
multiple tabs can be different threads. MS word uses multiple threads, one thread to format the
text, other thread to process inputs, etc.
Threads operate faster than processes due to following reasons:

1) Thread creation is much faster.


2) Context switching between threads is much faster.
3) Threads can be terminated easily
4) Communication between threads is faster.

Can we write multithreading programs in C?


Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or
Pthreads) is a POSIX standard for threads. Implementation of pthread is available with gcc
compiler.

Threads Operations:
Threads and processes have common operations
• Create
• Exit (terminate)
• Suspend
• Resume
• Sleep
• Wake
Thread Libraries:
• A thread library provides the programmer an API for creating and managing threads.
• There are two primary ways of implementing a thread library.
• The first approach is to provide a library entirely in user space with no kernel support.
All code and data structures for the library exist in user space. This means that invoking
a function in the library results in a local function call in user space and not a system
call.
• The second approach is to implement a kernel-level library supported directly by the
operating system. In this case, code and data structures for the library exist in kernel
space. Invoking a function in the API for the library typically results in a system call to
the kernel.

Three main thread libraries are in use today:


• POSIX Pthreads,
• Win32, and
• Java threads
Pthreads:

• May be provided as either a user or kernel library, as an extension to the POSIX standard.
• The POSIX standard ( IEEE 1003.1c ) defines the specification for pThreads, not the
implementation.
• pThreads are available on Solaris, Linux, Mac OSX, Tru64
• In a Pthreads program, separate threads begin execution in a specified function.
• Global variables are shared amongst all threads.
• One thread can wait for the others to rejoin before continuing.
• UNIX and Linux systems often use Pthreads.

Windows Threads:

• The Win32 thread library is a kernel-level library available on Windows systems.


• Implements the one-to-one mapping.
• Each thread contains
o a thread id
o register set
o separate user and kernel stacks
o private data storage area
Java Threads:

• The Java thread API allows thread creation and management directly in Java programs.
However, because in most instances the JVM is running on top of a host operating system,
the Java thread API is typically implemented using a thread library available on the host
system.
• This means that on Windows systems, Java threads are typically implemented using the
Win32 API.
• Java threads are managed by the JVM.

A simple C program to demonstrate use of pthread basic functions:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep().
#include <pthread.h>
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
void *myThreadFun(void *vargp)
{
sleep(1);
printf("Printing GeeksQuiz from Thread \n");
return NULL;
}
int main()
{
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
printf("After Thread\n");
exit(0);
}
Please note that this program may compile only with C compilers with pthread library.
Explanation:

• In main() we declare a variable called thread_id, which is of type pthread_t, which is an


integer used to identify the thread in the system.
• After declaring thread_id, we call pthread_create() function to create a thread.
pthread_create() takes 4 arguments.
▪ The first argument is a pointer to thread_id which is set by this function.
▪ The second argument specifies attributes. If the value is NULL, then default
attributes shall be used.
▪ The third argument is name of function to be executed for the thread to be created.
▪ The fourth argument is used to pass arguments to the function, myThreadFun.
• The pthread_join() function for threads is the equivalent of wait() for processes. A call to
pthread_join blocks the calling thread until the thread with identifier equal to the first
argument terminates.
How to compile above program?
To compile a multithreaded program using gcc, we need to link it with the pthreads library.
Following is the command used to compile the program.

A C program to show multiple threads with global and static variables:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int g = 0; // Let us create a global variable to change it in threads
void *myThreadFun(void *vargp) // The function to be executed by all threads
{
int *myid = (int *)vargp; // Store the value argument passed to this thread
static int s = 0; // Let us create a static variable to observe its changes
++s; // Change static and global variables
++g;
printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g); // Print the argument,
static and global variables
}
int main()
{ int i;
pthread_t tid
// Let us create three threads
for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, myThreadFun, (void *)&tid);
pthread_exit(NULL);
return 0;
}
Explanation:
As mentioned above, all threads share data segment. Global and static variables are stored in data
segment. Therefore, they are shared by all threads. The following example program demonstrates
the same.

Please note that above is simple example to show how threads work. Accessing a global variable
in a thread is generally a bad idea. What if thread 2 has priority over thread 1 and thread 1 needs
to change the variable. In practice, if it is required to access global variable by multiple threads,
then they should be accessed using a mutex.
Assignment:
1. Write a Program to create five threads, each executing the function perform_work that
prints the unique number of this thread to standard output. The strcture of perform_work
function is given below:
void *perform_work(void *arguments){
int index = *((int *)arguments);
int sleep_time = 1 + rand() % NUM_THREADS;
printf("THREAD %d: Started.\n", index);
//show value of global variable here
printf("THREAD %d: Will be sleeping for %d seconds.\n", index, sleep_time);
sleep(sleep_time);
printf("THREAD %d: Ended.\n", index);
}
2. Use a global/static variable which will be incremented by 2 in each thread and show its
value.this will show the communication of threads by using global or static variables.
Following is the structure of main function:
int main()
{
//define array of threads

//create all five threads one by one


printf("IN MAIN: All threads are created.\n");

// wait for each thread to complete

printf("MAIN program has ended.\n");


return 0;
}

You might also like