Synchronization Constructs ATOMIC Directive Atomic directive ch ra

  • Slides: 9
Download presentation
Synchronization Constructs

Synchronization Constructs

ATOMIC Directive • Atomic directive chỉ ra rằng một địa chỉ bộ nhớ phải

ATOMIC Directive • Atomic directive chỉ ra rằng một địa chỉ bộ nhớ phải được cập nhật một cách nguyên tử. • Cú pháp atomic directive: #pragma omp atomic new-line expression-stmt • Expression statement phải có dạng: • • • x += expr (+; -; *; /; >>; <<) x++ ++x x---x

 • Hạn chế: – Atomic directive chỉ áp dụng cho 1 câu lệnh

• Hạn chế: – Atomic directive chỉ áp dụng cho 1 câu lệnh – Một câu lệnh atomic phải có một cú pháp nhất định

FLUSH directive • Cú pháp: • #pragma omp flush (list) newline • Giả sử

FLUSH directive • Cú pháp: • #pragma omp flush (list) newline • Giả sử có nhiều thread cùng sử dụng một dữ liệu chung được chia sẻ. Trong đó, các thread có thể thay đổi giá trị của dữ liệu chung đó. • Vấn đề: Khi 1 thread thay đổi giá trị dữ liệu thì dữ liệu đã được cập nhật đến các Thread khác

FLUSH directive • Có 2 dạng Flush directive: – Flush directive with list –

FLUSH directive • Có 2 dạng Flush directive: – Flush directive with list – Flush directive without list

 • • • • • • // omp_flush. cpp // compile with: /openmp

• • • • • • // omp_flush. cpp // compile with: /openmp #include <stdio. h> #include <omp. h> void read(int *data) { printf_s("read datan"); *data = 1; } void process(int *data) { printf_s("process datan"); (*data)++; } int main() { int data; int flag; flag = 0;

 • • • • • • • #pragma omp parallel sections num_threads(2) {

• • • • • • • #pragma omp parallel sections num_threads(2) { #pragma omp section { printf_s("Thread %d: ", omp_get_thread_num( )); read(&data); #pragma omp flush(data) flag = 1; #pragma omp flush(flag) // Do more work. } #pragma omp section { while (!flag) { #pragma omp flush(flag) } #pragma omp flush(data) } } } printf_s("Thread %d: ", omp_get_thread_num( )); process(&data); printf_s("data = %dn", data);

Kết quả • Thread 0: read data • Thread 1: process data • data

Kết quả • Thread 0: read data • Thread 1: process data • data = 2

 • // omp_flush_without_list. c #include <omp. h> int x, *p = &x; void

• // omp_flush_without_list. c #include <omp. h> int x, *p = &x; void f 1(int *q){ *q = 1; #pragma omp flush // x, p, and *q are flushed // because they are shared and accessible // q is not flushed because it is not shared. }