1. Homepage
  2. Programming
  3. [2022] CS3214 Computer Systems - Project 2: A Fork-Join Framework

[2022] CS3214 Computer Systems - Project 2: A Fork-Join Framework

Engage in a Conversation
CS3214Computer SystemsProgramming HelpVirginia TechVirginia Polytechnic Institute and State UniversityA Fork Join Framework

CS3214 Spring 2022 Project 2 - “A Fork-Join Framework” CourseNana.COM

What to submit: Upload a tar ball using the p2 identifier that includes the following files:
-
partner.json with the SLO IDs in the format described for Project 1.
-
threadpool.c with your code. CourseNana.COM

- threadpool.pdf with your project description. Use a suitable word processing pro- gram to produce the PDF file.
We will be using the provided
fjdriver.py file to test your code. Please see Section 3.5 for more information. CourseNana.COM

1 Background CourseNana.COM

The last 2 decades have seen the widespread use of processors that support multiple cores that can act as independent CPUs. Today, even processors used in smartphones contain 4 or more cores. Software has been slow to catch up, despite calls for programming models that make it easy to write scalable programs for multicore systems [1]. CourseNana.COM

The reference documentation on cppreference.com provides the example shown in Figure 1. CourseNana.COM

This toy example sums up the elements of a vector, which here are initialized to 1, using a recursive divide-and-conquer approach. At each level of recursion, the array is subdi- vided into two equal parts, one of which is passed to std::async to be executed in a separate thread, whereas the other part is recursively performed by the calling thread. std::async returns a handle of type std::future, which represents a reference to a result of a computation that is executed asynchronously. When the computation’s result is needed, a thread may invoke the future’s get() method. get() will return the result, arranging for—or waiting for—its computation as necessary. CourseNana.COM

1   #include <iostream> CourseNana.COM

2   #include <vector> CourseNana.COM

3   #include <algorithm> CourseNana.COM

4   #include <numeric> CourseNana.COM

5   #include <future> CourseNana.COM

6      template <typename RAIter>
int parallel_sum(RAIter beg, RAIter end) { CourseNana.COM

7      auto len = std::distance(beg, end); if(len < 1000) CourseNana.COM

8           return std::accumulate(beg, end, 0); CourseNana.COM

9      RAIter mid = beg + len/2;
auto handle = std::async(std::launch::async, CourseNana.COM

10   parallel_sum<RAIter>, mid, end); int sum = parallel_sum(beg, mid); CourseNana.COM

11   return sum + handle.get(); } CourseNana.COM

12   int main() { CourseNana.COM

13   std::vector<int> v(100000000, 1);
std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) CourseNana.COM

14   << ’\n’; CourseNana.COM

15   } CourseNana.COM

Compiling and running this program under g++ 8.5.0 one obtains the following output: CourseNana.COM

$ g++ -pthread -O2 cppasyncpsum.cc -o cppasyncpsum
$ ./cppasyncpsum
terminate called after throwing an instance of ’std::system_error’
  what():  Resource temporarily unavailable Aborted (core dumped) CourseNana.COM

In this project, you will create a small fork/join framework that allows the parallel execution of divide-and-conquer algorithms such as the one shown in the example in Figure 1 in a resource-efficient manner. To that end, you will create a thread pool implementation for dynamic task parallelism, focusing on the execution of so-called fork/join tasks. Your implementation should avoid excessive resource use in order to avoid crashes like the one seen in this example. CourseNana.COM

2 Thread Pools and Futures CourseNana.COM

Your fork-join thread pool should implement the following API: CourseNana.COM

1      /* Opaque forward declarations. The actual definitions of these types will be local to your threadpool.c implementation. */ CourseNana.COM

2      struct thread_pool; struct future; CourseNana.COM

3   /* Create a new thread pool with no more than n threads. */ CourseNana.COM

4      struct thread_pool * thread_pool_new(int nthreads); CourseNana.COM

5      /*
* Shutdown this thread pool in an orderly fashion.
* Tasks that have been submitted but not executed may or may not be executed.  Deallocate the thread pool object before returning. */ CourseNana.COM

6      void thread_pool_shutdown_and_destroy(struct thread_pool *); CourseNana.COM

7     
typedef void * (* fork_join_task_t) (struct thread_pool *pool, void * data); CourseNana.COM

8   /* Submit a fork join task to the thread pool and return afuture. The returned future can be used in future_get()  to obtain the result. CourseNana.COM

9      *  ’pool’ - the pool to which to submit CourseNana.COM

10   *  ’task’ - the task to be submitted. CourseNana.COM

11   *  ’data’ - data to be passed to the task’s function * CourseNana.COM

12   *  Returns a future representing this computation. */ CourseNana.COM

13   struct future * thread_pool_submit( struct thread_pool *pool, fork_join_task_t task, void * data); CourseNana.COM

14   /* Make sure that the thread pool has completed the execution  of the fork join task this future represents. Returns the value returned by this task. */
void * future_get(struct future *); CourseNana.COM

15 /* Deallocate this future. Must be called after future_get() */ CourseNana.COM

16   void future_free(struct future *); CourseNana.COM

2.1 Work Stealing CourseNana.COM

There are at least two common ways in which multiple threads can share the execution of dynamically created tasks: work sharing and work stealing. In a work sharing approach, tasks are submitted to a single, central queue from which all threads remove tasks. The drawback of this approach is that this central queue can become a point of contention, particularly for applications that create many small tasks. CourseNana.COM

Instead, a work stealing approach is recommended [2] which has been shown to (at least potentially) lead to better load balancing and lower synchronization requirements. In a work stealing pool, each worker thread maintains its own local queue of tasks, as shown in Figure 2. Each queue is a double-ended queue (deque) which allows insertion and removal from both the top and the bottom. When a task run by a worker spawns a new task, it is added (pushed) to the bottom of that worker’s queue. Workers execute tasks by popping them from the bottom, thus following a LIFO order. If a worker runs out of tasks, it checks a global submission queue for tasks. If a task can be found in it, it is executed. Otherwise, the worker attempts to steal tasks to work on from the top of other threads’ queues. CourseNana.COM

In this assignment, you are asked to implement a work stealing thread pool. Since work stealing is purely a performance optimization, you may for reduced credit (corresponding to a B letter grade) implement a work sharing approach. CourseNana.COM

2.2 Helping CourseNana.COM

A naive attempt at implementing future get would have the calling thread block if the task associated with that future has not yet been computed. “Blocking” here means to wait on a synchronization device such as a semaphore until it is signaled by the thread computing the future. However, this approach risks thread starvation: if a worker thread blocks while attempting to call future get it is easily possible for all worker threads to be blocked on futures, leading to a deadlock because no worker threads are available to compute the tasks on which the workers are blocked! CourseNana.COM

Instead, worker threads that attempt to resolve a future that has not yet been computed must help in its execution. If the future’s task has not yet started executing, the worker should steal it and execute it itself. If it has started executing, the worker has two choices: it could wait for it to finish, or it could help by executing tasks spawned by the task being joined, hoping to speed up its completion. CourseNana.COM

For the purposes of this assignment, we assume a fully-strict model as defined in [2]. A fully-strict model requires that tasks join tasks they spawn — in other words, every call to submit a task has a matching call to future get() within the same function invocation. In this sense, all tasks spawned by a task can be considered subtasks that need to complete before the task completes. All our tests will be fully strict computations, which encompass a wide range of parallel computations. CourseNana.COM

Restricting ourselves to fully-strict computation for this project simplifies helping because it is always safe for workers intending to help to steal any task as long as they steal from the top of any other worker’s queue. Safety here refers to the absence of execution dead- lock. CourseNana.COM

Note that in a fully-strict model, in combination with helping, worker threads will never be in a situation where they are looking for tasks on their own queue: this is because any subtask spawned from a task they were working on will be joined before that task returns. In this situation, the worker will either directly execute that task via helping, or the task will have been stolen by some other worker. In no case will a worker return from executing a task and find other, unfinished tasks on its queue. (Recall that all tasks added to a worker thread’s queue are subtasks of a task the worker was executing at the time.) CourseNana.COM

2.3 Implementation CourseNana.COM

Except for constraints imposed by the API and resource availability, you have complete freedom in how to implement your thread pool. Numerous strategies for stealing, help- ing, blocking, and signaling are possible, each with different trade-offs. CourseNana.COM

You will need to design a synchronization strategy to protect the data structures you use, such as flags representing the execution state of each tasks, the local queues, and the global submission queue, and possibly others. You will need a signaling strategy so that worker threads learn about the availability of tasks in the global queue or in other threads’ queues. CourseNana.COM

2.4 Basic Strategy CourseNana.COM

A basic strategy would be to use locks, condition variables, and the provided list imple- mentation (known to you from prior projects), which allows constant-time insertion and removal of list elements and which can be used to implement a deque. CourseNana.COM

You will have to define private structures struct future and struct thread pool in threadpool.c. A future should store a pointer to the function to be called, any data to be passed to that function, as well as the result (when available). You will have to define appropriate variables to record the state of a future, such as whether its execution has started, is in progress, or has completed, as well as which queue the future is in to keep track of stealing. CourseNana.COM

A thread pool should keep track of a global submission queue, as well as of the worker threads it has started. In the work stealing approach, each worker thread requires its own queue. You will also need a flag to denote when the thread pool is shutting down. CourseNana.COM

You will need to create a static function that performs the core work of each worker thread. You will pass this function to pthread create(), along with an argument (such as a pointer to a preallocated struct) allowing the thread to identify its position in the worker pool and to obtain a reference to the pool itself. CourseNana.COM

thread pool submit(). You should allocate a new future in this function and submit it to the pool. Since the same API is used for external submissions (from threads that are not part of the pool) and internal submissions (from threads that are part of the pool), you will need to use a thread-local variable to distinguish those cases. The thread local variable could be used to quickly look up the information pertaining to the submitting worker thread for internal submissions. CourseNana.COM

future get(). The calling thread may have to help in completing the future being joined, as described in Section 2.2. Helping is required for both work sharing and work stealing approaches. CourseNana.COM

thread pool shutdown and destroy(). This function will shut down the thread pool. Al- ready executing futures must complete; queued futures may or may not complete. CourseNana.COM

The calling thread must join all worker threads before returning. Do not use pthread cancel() because this function does not ensure that currently executing futures run to completion; instead, use a flag and an appropriate signaling strategy. CourseNana.COM

Upon destruction, a threadpool should have deallocated all memory that we allocated on behalf of the worker threads. CourseNana.COM

future free(). Frees the memory for a future instance allocated in thread pool submit(). This function is called by the client. Do not call it in your thread pool implementation. CourseNana.COM

2.5 Advanced Strategies/Extra Credit CourseNana.COM

Real-world fork/join implementations employ a number of optimizations designed to minimize per-task synchronization overhead. For instance, a crucial optimization is to speed up the common case of adding an element to or removing it from the bottom of a worker’s queue. This optimization is possible because only the current worker may add tasks to the queue, and only the current worker removes task from the bottom of its queue. Stealers remove tasks from the top of the queue. CourseNana.COM

The first optimized implementations used the THE protocol, inspired by Djikstra’s mu- tual exclusion algorithm [4], which is further described in [5] and [6]. Chase and Lev presented a version of a work-stealing deque in [3], but their paper contains a number of errors. A corrected version using C11 atomics is presented by Leˆ et al. [7], whose code CourseNana.COM

A second possible extension would be to support computations that are not fully-strict, but still recursive. We define “recursive” such that it is possible to execute them on a single worker thread using helping, even though they do not meet the definition of being fully strict, perhaps because futures are passed among tasks before being joined. CourseNana.COM

If the computation is not fully-strict but still recursive, a deadlock situation could arise where one worker steals a task that, in order to complete, requires the results of a task whose execution has been started by the stealing thread, but not yet finished. Systems such as CILK [5] avoid this by using a technique known as continuation stealing [8] in which it is possible for other worker threads to continue (and complete) a spawning task. However, continuation stealing requires compiler support since another thread would CourseNana.COM

A third possible extension would be to support fully general acyclic computational graphs. (The assumption of being acyclic is necessary because graphs with cyclic dependencies are impossible to schedule.) Note that the given API is not suited for arbitrary depen- dency DAGs in the presence of child stealing. To support arbitrary DAGs in the absence of continuation stealing, an inverted control flow model must be used, perhaps similar to that used in Java’s CountedCompleter classes. In other words, such tasks are not joined, but rather a callback will be executed once they complete, allowing dependent tasks to be scheduled. CourseNana.COM

If you implement any of these strategies, be sure to discuss it in your project description so that TAs may award extra credit if warranted. CourseNana.COM

3 Additional Notes
3.1 Semaphores vs Condition Variables CourseNana.COM

We do not recommend that you use semaphores to signal your worker threads regarding the availability of new tasks, because semaphores do not perform well in the presence of large numbers of signals. Recall that signaling a semaphore entails incrementing its in- ternal count, which requires an atomic write operation on its internal state. In the context of cache-coherent multiprocessors, this causes a transition into the modified state in the accessing core’s cache, which causes a frequently updated semaphore to ping pong be- tween caches. By contrast, condition variables are implemented in a way that handles the common case of signaling with no waiter present using the shared state - the condition variable records if any waiters are present and does not require updating state when a call to pthread cond signal does not signal any threads. In addition, we recommend that you intentionally break the rule of signaling with the lock held (which Helgrind otherwise warns you about) for this case, while making sure to not lose wakeups indefinitely. CourseNana.COM

You may still find semaphores useful, potentially, to implement waiting on individual tasks. CourseNana.COM

3.2 Avoiding False Sharing CourseNana.COM

As you tune the performance of your implementation, be on the outlook for false sharing. False sharing occurs when per-thread data structures are allocated within the same cache line, which may happen, for instance, for neighboring array elements. A potential mistake is to have a contiguous array of per-thread (per-worker) structures which are not meant to be shared but allocated closely together. To avoid this, add padding to ensure they in different cache lines. CourseNana.COM

Get in Touch with Our Experts

WeChat (微信) WeChat (微信)
Whatsapp WhatsApp
CS3214代写,Computer Systems代写,Programming Help代写,Virginia Tech代写,Virginia Polytechnic Institute and State University代写,A Fork Join Framework代写,CS3214代编,Computer Systems代编,Programming Help代编,Virginia Tech代编,Virginia Polytechnic Institute and State University代编,A Fork Join Framework代编,CS3214代考,Computer Systems代考,Programming Help代考,Virginia Tech代考,Virginia Polytechnic Institute and State University代考,A Fork Join Framework代考,CS3214help,Computer Systemshelp,Programming Helphelp,Virginia Techhelp,Virginia Polytechnic Institute and State Universityhelp,A Fork Join Frameworkhelp,CS3214作业代写,Computer Systems作业代写,Programming Help作业代写,Virginia Tech作业代写,Virginia Polytechnic Institute and State University作业代写,A Fork Join Framework作业代写,CS3214编程代写,Computer Systems编程代写,Programming Help编程代写,Virginia Tech编程代写,Virginia Polytechnic Institute and State University编程代写,A Fork Join Framework编程代写,CS3214programming help,Computer Systemsprogramming help,Programming Helpprogramming help,Virginia Techprogramming help,Virginia Polytechnic Institute and State Universityprogramming help,A Fork Join Frameworkprogramming help,CS3214assignment help,Computer Systemsassignment help,Programming Helpassignment help,Virginia Techassignment help,Virginia Polytechnic Institute and State Universityassignment help,A Fork Join Frameworkassignment help,CS3214solution,Computer Systemssolution,Programming Helpsolution,Virginia Techsolution,Virginia Polytechnic Institute and State Universitysolution,A Fork Join Frameworksolution,