The format for the second midterm exam will be the same as the first midterm exam: an in-class, written exam. On the exam I will ask short-answer questions that will ask you to write short code snippets.
The exam will be a closed-book exam, but I will allow you to bring a single page of notes to use as a reference in the exam.
One problem I will ask will be very similar to the threads problem I asked on the first midterm. For this problem you should be familiar with some of the thread management functions:
pthread_create() pthread_join()
You should also know how to write a thread function.
Here is the thread problem from the first exam, along with my solution:
You need to compute the sum of a list of integers. The list is very large, so you decide to use threads to do the sum more quickly. Assume that you have defined a struct
typedef struct { int* A; // Pointer to array of ints int start; // Where the subrange starts int end; // Where the subrange ends int sum; } range;
that can describe a subrange of an array and the sum of the numbers in that subrange. Write the code for a function
int sum(int* A,int N)
that can compute the sum of the integers in the array that A points to. N is the number of integers in the array. In your function you decide to break the set of numbers to be summed into four subranges and then use four separate threads to compute the sums of those subranges. In your function make use of an array
range R[4];
Write the code for the sum()
function and the thread function you will use.
void* sumRange(void* arg) { range* r = (range*) arg; for(int n = r->start;n < r->end;n++) r->sum += r->A[n]; return NULL; } int sum(int* A,int N) { pthread_t tids[4]; range R[4]; int n; for(n = 0;n < 4;n++) { R[n].A = A; R[n].sum = 0; } R[0].start = 0; R[0].end = R[1].start = N/4; R[1].end = R[2].start = N/2; R[2].end = R[3].start = 3*N/4; R[3].end = N; for(n = 0;n < 4;n++) pthread_create(&tids[n],NULL,sumRange,&R[n]); int total = 0; for(n = 0;n < 4;n++) { pthread_join(tids[n],NULL); total += R[n].sum; } return total; }
Here is a new list of system calls that we have worked with since the first midterm. You should be familiar with each of these functions and should be prepared to use them in code.
signal() sigemptyset() sigaddset() sigprocmask() sigwait() opendir() readdir() rewinddir() closedir() epoll_create() epoll_ctl() epoll_wait()
Since I may ask about signals you should also be prepared to write the code for a signal handler.