Добавил:
ivanov666
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Распараллеливание программ. Учебник
.pdf
121
if (print_primes) printf(«%5d is prime\n»,i);
number_of_primes++;
if (i%4 == 1) number_of_41primes++;
if (i%4 == 3) number_of_43primes++;
}
}
#pragma omp parallel for private(i,limit,prime,j)
for(i = start; i <= end; i += 2) {
limit = (int) sqrt((float)i) + 1;
prime = 1; /* assume number is prime */
j = 3;
while (prime && (j <= limit)) {
if (i%j == 0) prime = 0;
j += 2;
}
if (prime) {
if (print_primes) printf(“%5d is prime\n”,i);
#pragma critical
{
number_of_primes++;
if (i%4 == 1) number_of_41primes++;
if (i%4 == 3) number_of_43primes++;
}
}
}
#pragma omp parallel for private(i,limit,prime,j)
for(i = start; i <= end; i += 2) {
limit = (int) sqrt((float)i) + 1;
prime = 1; /* assume number is prime */
j = 3;
while (prime && (j <= limit)) {
if (i%j == 0) prime = 0;
j += 2;
}
if (prime) {

122
if (print_primes) printf(«%5d is prime\n»,i);
#pragma critical(cs1)
number_of_primes++;
#pragma critical(cs2)
if (i%4 == 1) number_of_41primes++;
#pragma critical(cs3)
if (i%4 == 3) number_of_43primes++;
}
}
#pragma omp parallel for private(i,limit,prime,j)
for(i = start; i <= end; i += 2) {
limit = (int) sqrt((float)i) + 1;
prime = 1; /* assume number is prime */
j = 3;
while (prime && (j <= limit)) {
if (i%j == 0) prime = 0;
j += 2;
}
if (prime) {
if (print_primes) printf(«%5d is prime\n»,i);
# pragma atomic
number_of_primes++;
if (i%4 == 1) {
# pragma atomic
number_of_41primes++;
}
if (i%4 == 3) {
# pragma atomic
number_of_43primes++;
}
}
}

123
#pragma omp parallel for private(i,limit,prime,j) \
reduction(+:numberOfPrimes, \
numberOf41primes,numberOf43primes)
for(i = start; i <= end; i += 2) {
limit = (int) sqrt((float)i) + 1;
prime = 1; /* assume number is prime */
j = 3;
while (prime && (j <= limit)) {
if (i%j == 0) prime = 0;
j += 2;
}
if (prime) {
if (print_primes) printf(«%5d is prime\n»,i);
numberOfPrimes++;
if (i%4 == 1) numberOf41primes++;
if (i%4 == 3) numberOf43primes++;
}
}

124
БИБЛИОТЕКА POSIX® thread
®

125
®
Типы данных pthread
Таблица 1
Тип Описание
pthread_t
pthread_mutex_t
pthread_cond_t
pthread_spinlock_t
pthread_rwlock_t
pthread_barrier_t
pthread_key_t
pthread_attr_t
pthread_mutexattr_t
pthread_condattr_t
pthread_rwlockattr_t
pthread_barrierattr_t
pthread_once_t
идентификатор нити
мьютекс
условная переменная
спин-блокировка (2001)
блокировка записи/чтения (2001)
барьер (2001)
ключ доступа
атрибут нити
атрибут мьютекса
атрибут условной переменной
атрибуты блокировки записи/чтения (2001)
атрибуты барьера (2001)
контекст однократной инициализации
®
pthread_t

126
Управление нитями
функцию нити
локальной памяти нити
отсоединенные
Таблица 2
Состояние Описание
Ready Нить готова к выполнению, но ждет доступа к процессору.
Running Нить в настоящий момент выполняется на процессоре. На многопро-
цессорных или многонитевых (SMT/HyperThreading
быть более одной выполняющейся нити.
Blocked Нить не может выполняться, так как ждет наступления какого-либо со-
бытия. Например, захвата мьютекса или завершения операции ввода/
вывода.
Terminated Нить завершилась или была отменена, но не была ни ранее отсоеди-
нена, ни после этого присоединена.
®
) системах может
pthread_create

127
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start)(void *), void *arg);
pthread_t
NULL
pthread_t thread;
void *thread_func(void *data) {
/* тело функции выполняющейся в новой нити ... */
}
int main()
{ pthread_t id;
/* ... */
pthread_create(&id, NULL, &thread_func, NULL);
/* ... */
}
pthread_self
pthread_t pthread_self(void);
pthread_equal
int pthread_equal(pthread_t t1, pthread_t t2);
int pthread_exit(void *value_ptr);

128
int pthread_join(pthread_t thread, void **value_ptr);
CANCELLED
PTHREAD_
нельзя
create()
pthread_
int pthread_detach(pthread_t thread)
int sched_yield(void);
необходимостью
sched_yield()

129
pthread_
cancel()
int pthread_cancel(pthread_t thread);
• Отменяемая
• Асинхронно отменяемую
• Синхронно отменяемую
• Неотменяемая
int pthread_setcancelstate(int state,
int *oldstate);
int pthread_setcanceltype();(int type,
int *oldtype);
Значения параметров state/type
Параметр Имя константы
state PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DISABLE
type PTHREAD_CANCEL_DEFERRED
PTHREAD_CANCEL_ASYNCHRONOUS
void pthread_testcancel(void);

130
int pthread_once(pthread_once_t *once_control,
void (*init_routine) (void));
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr);
int pthread_attr_setdetachstate(pthread_attr_t *attr,
int detachstate);
int pthread_attr_getdetachstate(
const pthread_attr_t *attr,
int *detachstate);
PTHREAD_CREATE_JOINABLE нить создавать присоединяемой
PTHREAD_CREATE_DETACHED нить создавать отсоединенной
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]
