Threads programming

Thread overview

Target hardware
Multi-socket motherboards
1
- Intel Sandy Bridge CPU. 
Intel Sandy Bridge CPU
Thread: An abstraction for running multiple processes
Threads memory model
POXIS threads (pthreads)
Say hello to my little threads …
File/Open Folder
/home/student
Create new folder/file

```c linenums=”1” –8<– “docs/csc466/lectures/data/thread/hello_thread.c”

1
2
3
4
5
6
7
8
- Compile and run `thread_hello.c`:

```bash
gcc -o thread_hello thread_hello.c -lpthread
./thread_hello 1
./thread_hello 2 
./thread_hello 4

Thread parallelization

Sum of values in an array

```c linenums=”1” –8<– “docs/csc466/lectures/data/thread/thread_sum.c”

1
2
3
4
5
6
7
8
- Compile and run `thread_sum.c`:

```bash
gcc -o thread_sum thread_sum.c -lpthread
./thread_sum 16 4
./thread_sum 256 4
./thread_sum 1000000 4
Global variable: does it work?

```c linenums=”1” –8<– “docs/csc466/lectures/data/thread/thread_global_nolock.c”

1
2
3
4
5
6
7
8
9
10
- Compile and run `thread_global_nolock.c`:
  - Compare the outcome with `thread_sum`

```bash
gcc -o thread_global_nolock thread_global_nolock.c -lpthread
./thread_global_nolock 16 4
./thread_global_nolock 2000 4
./thread_global_nolock 90000 4
./thread_sum 90000 4
What is the problem?
Multi-socket motherboards
Key definitions
Requirements for critical section handling
Lock: Definition
Semantic of locking: lock() and unlock()
Global variable: correction at a cost

```c linenums=”1” –8<– “docs/csc466/lectures/data/thread/thread_global_lock.c”

1
2
3
4
5
6
7
8
9
10
11
12
13
- Compile and run `thread_global_lock.c`:
  - Compare the outcome with `thread_sum`
  - Compare the runtime with `thread_sum` and `thread_global_nolock` with a lower input value

```bash
gcc -o thread_global_lock thread_global_lock.c -lpthread
./thread_global_lock 90000 4
./thread_global_nolock 90000 4
./thread_sum 90000 4
./thread_global_lock 2000 4
./thread_global_nolock 2000 4
./thread_sum 2000 4