Lab 07 - Programming Threads
Lab 07 - Programming Threads
Objectives
Tools/Software Requirement
Description
1. POSIX Threads, or Pthreads, is a POSIX standard for threads. The standard, POSIX.1c,
Threads extensions (IEEE Std 1003.1c-1995), defines an API for creating and
manipulating threads.
2. Implementations of the API are available on many Unix-like POSIX systems such
as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris, but Microsoft
Windows implementations also exist. For example, the pthreads-w32 is available and
supports a subset of the Pthread API for the Windows 32-bit platform.
3. The POSIX standard has continued to evolve and undergo revisions, including the
Pthreads specification. The latest version is known as IEEE Std 1003.1, 2004 Edition.
4. Pthreads are defined as a set of C language programming types and procedure calls,
implemented with a pthread.h header file. In GNU/Linux, the pthread functions are not
included in the standard C library. They are in libpthrea, therefore, we should add -
lpthread to link our program.
1. Thread management:
Routines that work directly on threads - creating, detaching, joining, etc. They also include
functions to set/query thread attributes such as joinable, scheduling etc.
2. Mutexes:
Routines that deal with synchronization, called a "mutex", which is an abbreviation for "mutual
Creating Threads
1. Our main() program is a single, default thread. All other threads must be explicitly
created by the programmer.
2. pthread_create creates a new thread and makes it executable. This routine can be called
any number of times from anywhere within our code.
3. pthread_create (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)
(void *), void *arg) arguments:
1. thread:
An identifier for the new thread returned by the subroutine. This is a pointer
to pthread_t structure. When a thread is created, an identifier is written to the
memory location to which this variable points. This identifier enables us to refer
to the thread.
2. attr:
An attribute object that may be used to set thread attributes. We can specify a
thread attributes object, or NULL for the default values.
3. start_routine:
The routine that the thread will execute once it is created.
void *(*start_routine)(void *)
// thread0.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pthread_t my_thread;
int ret;
pthread_exit(NULL);
}
In the code, the main thread will create a second thread to execute worker_thread(), which will
print out its message while main thread prints another. The call to create the thread has a NULL
value for the attributes, which gives the thread default attributes. The call also passes the address
of a my_thread variable for the worker_thread() to store a handle to the thread. The return
value from the pthread_create() call will be zero if it's successful, otherwise, it returns an error.
Output:
// thread01.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
pthread_t my_thread[N];
long id;
for(id = 1; id <= N; id++) {
int ret = pthread_create(&my;_thread[id], NULL, &worker;_thread, (void*)id);
if(ret != 0) {
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
This is worker_thread #5
This is worker_thread #4
This is worker_thread #3
This is worker_thread #2
This is worker_thread #1
Note that, in the code, we pass the parameter (thread id) to the child thread.
If we do (void*)&id, it's a wrong way of passing data to the child thread. It passes the address of
variable id, which is shared memory space and visible to all threads. As the loop iterates, the
value of this memory location changes, possibly before the created threads can access it.
Attributes of Threads
1. By default, a thread is created with certain attributes. Some of these attributes can be
changed by the programmer via the thread attribute object.
2. pthread_attr_init() and pthread_attr_destroy() are used to initialize/destroy the thread
attribute object.
3. Other routines are then used to query/set specific attributes in the thread attribute object.
Terminating Threads
Join
A thread can execute a thread join to wait until the other thread terminates. In our case, you - the
main thread - should execute a thread join waiting for your colleague - a child thread - to
1. When P executes a thread join in order to join with C, which is still running, P is
suspended until C terminates. Once C terminates, P resumes.
2. When P executes a thread join and C has already terminated, P continues as if no such
thread join has ever executed (i.e., join has no effect).
A parent thread may join with many child threads created by the parent. Or, a parent only join
with some of its child threads, and ignore other child threads. In this case, those child threads that
are ignored by the parent will be terminated when the parent terminates.
1. The pthread_join() subroutine blocks the calling thread until the specified thread
terminates.
2. The programmer is able to obtain the target thread's termination return status if it was
specified in the target thread's call to pthread_exit() as show here:
int main()
{
int i;
pthread_t thread;
pthread_create(&thread;, NULL, worker_thread, NULL);
pthread_join(thread, (void **)&i);
printf("%d\n",i); // will print out 911
}
3. A joining thread can match one pthread_join() call. It is a logical error to attempt
multiple joins on the same thread.
Tasks
1. Implement a simple program using for loop to calculate the sum of first 100 million positive
integers (i.e., 100,000,000) elements in an array.
3. Run the above code several time to verify that the threads runs concurrently and threads
execution varies in each run.
4. Use the code in task 1 and 2 to print the time each program takes to execute. Which program
runs faster and why?
Deliverables
Submit the document containing code and screenshot for of your programs, along with the
answer to the last question. You are supposed to strictly follow submission guidelines.
References:
https://www.cs.cmu.edu/afs/cs/academic/class/15492-f07/www/pthreads.html
https://www.includehelp.com/c/sum-of-an-array-using-multithreading-in-c-cpp.aspx