Changes

Jump to: navigation, search

GPU621/NoName

1,041 bytes added, 04:34, 3 December 2016
Mutual Exclusion
C++ 11 threads and language native threads unfortunately lack this luxury. In order to parallelize a loop using std Threads, it is the programmers responsibility to calculate the range of each iteration within the loop the be parallelized. This is usually done using SPMD techniques.
====Mutual ExclusionSynchronization==== C++ 11 and Openmp are designed to avoid race conditions and share data between threads in various ways.  ===Shared Memory===
=====OpenMp=====
 
Openmp uses the shared clause to define what variables are shared among all threads. All threads within a team access the same storage area for shared variables.
 
The he shared clause would be located within a pragma statement. The clause is defined as follows.
shared(var)
=====C++ 11=====
The atomic class provides an atomic object type which can eliminate the possibility of data races by providing synchronization between threads.
Accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses.
<br>
Atomic types are defined as
std::atomic<type> var_name;
 
===Mutual Exclusion===
=====OpenMp=====
Openmp Handles Mutual Exclusion by
=====C++ 11=====
• try_lock - tries to lock the mutex, returns if the mutex is not available
The atomic class provides an atomic object type which can eliminate the possibility Example of data races by providing synchronization between threads. Accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses. locking/blocking #include <iostream> #include <thread> #include <string> #include <brmutex>Atomic types are defined as std::mutex mu; void shared_output(std::atomicstring msg, int id) { mu.lock(); std::cout << msg <<type":" << id << std::endl; mu.unlock(); } void thread_function() { for (int i = -1000; i < 0; i++) shared_output("thread ", i); } int main() { std::thread t(&thread_function); for (int i = 1000; i > var_name0; i--) shared_output("main thread", i); t.join(); return 0; }
====Implementations====

Navigation menu