---
tags: OS
---
# OS Homework 3: Multithread Programming
105042015 沈冠妤 外語20
## :memo: Code Explain
### Main program():
* Include libraries
* Self defined type "data", indicating the array to be sorted, and the indexes of left, mid, right.

* Open files (input testcases and output .txt)
* Define threads, time variables, and input
* Define a buffer to save the numbers collected by while-loop (next step)

* Use a while-loop to collect every character (number)
* If it collects a white-space, save the numbers in the buffer, and clear the buffer.
* Keep track of the number of numbers in each line (index_of_num).

* If it collects a '\n', we start the merge sort because we had received all numbers in a line.
* Get the initial index of left, mid, and right.
* Left index will be 0
* Mid index will be (length of array)/2
* Right index will be length of array
* Start the clock
* Create two threads for sorting (sort the left and right array)
* Join the threads
* Create a thread for merging (merge the segmented arrays)
* Join the thread
* Get time from the clock
* Output results and time


* Close files (input testcases and output .txt)

### Merge sort():
Implemented **recursively**:
* Calculate mid index to separate an array into two.
* Left array and right array do merge sort.
* Merge the two arrays.

Merging:
* Retrieve the left array and the right array by input indexes.
* Merge the two arrays by comparing the first elements of the two arrays. Stop until one of the array is empty
* If left array's first element is smaller, input left array's first element.
* If right array's first element is smaller, input right array's first element.

* One of the array might be empty first. Keep output the non-empty array's element, until both array are empty

## :memo: Result Screen Shot
(Last output is testcase written by myself)

## :memo: Reference
[Initialize an array in C/C++ - hemingwaylee](https://coherence0815.wordpress.com/2016/07/11/initialize-an-array-in-cc/)
[atoi()用法](http://tw.gitbook.net/c_standard_library/c_function_atoi.html)
[Segmentation fault](https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/560380/)