Threads (ITS8020)

Allikas: Kursused
Redaktsioon seisuga 12. oktoober 2018, kell 08:42 kasutajalt Irve (arutelu | kaastöö) (Uus lehekülg: '{{Its8020}} This lab will deal with threads, their creation and common data protection. For (more than thorough) explanation on threads, you can read [https://computing.llnl.gov/...')
(erin) ←Vanem redaktsioon | Viimane redaktsiooni (erin) | Uuem redaktsioon→ (erin)
Mine navigeerimisribale Mine otsikasti

This lab will deal with threads, their creation and common data protection. For (more than thorough) explanation on threads, you can read POSIX Threads Programming. Threads and mutexes can be used for experimenting with concurrency with sharing of the memory space: something which could happen while programming a chip.

Compilation

You will note that using

#include <pthread.h>

in your program is not enough. It will still not compile. This is due to the fact that gcc needs additional library information and should be executed with -pthread option.

It would be helpful to use a makefile for further compilation. Create a file named Makefile in the directory of the program with contents similar to following (assuming that you named your program "threaded_hello.c"):

all: threaded_hello

threaded_hello: threaded_hello.c
        gcc -pthread threaded_hello.c -o threaded_hello.o

Use [tab] button for indentation. For compilation, write "make" or "make threaded_hello". For further information, refer to Makefile tutorial.

Task

As before you should make some test programs to run with threads. Keep the main() function as simple as possible, doing most of the "work" in threads.

1. Write and run a threaded "Hello, World" program. You need thread creation pthread_create() and pthread_join() commands.

2. Write a program which uses two threads which both run 100000 times while adding 1 to a single shared variable (global variable). It will (hopefully) not count correctly due to race conditions.

3. Modity the program to use detached threads. Note that you might want to call pthread_exit() from the main function to let the threads finish.

4. We need to protect the shared variable using a mutex. Use pthread_mutex_* functions. The logic to mutex is that you have to acquire mutex before doing work with shared data and have to release it after finishing with it. While the mutex is in the hands of a thread, the other threads who want to lock it block (wait) until the lock is released. Show it

5. For the last task, we explore how you could pass several arguments to a thread. Improve your program by adding two arguments for a thread that will run: the arguments should be the arguments to the program (to main()); pass them to the thread using an argument to the pthread_create() function. Running your program as follows:

threadexperiment test1 test2

The output should be as follows:

Hello, test1 test2

If there are less than 2 arguments, exit. Show it