7. Como aproveitar isso tudo?
APIs nativas para multithreading demandam
experiência para escrever código correto e eficiente
– Mais complexo para expandir, especialmente para sistemas
que usam outros processos multithreaded.
Instruções de vetorização também apresentam desafios
– Inline assembly e intrinsics requerem experiência de baixo
nível e não escalam facilmente
– A vetorização feita pelo compilador é bem-vinda, mas pode
não funcionar sempre. Além disso, pode ser prejudicada pela
semântica da linguagem.
9. Intel® Cilk™ Plus: solução simples e eficiente
Intel Cilk
Plus
Benefícios
Intel Cilk
Plus
O que é?
• Suportado pelo compilador:
3 simples palavras-chave
• Array notation
• Hyperobjects – evitam races de forma eficiente
• Pragmas e atributos para definir vetorização
• Suporta C and C++
• Sintaxe fácil de aprender e usar
• Código rápido e reutilizável (vetores maiores)
• Fork/join: simples de entender,
reproduz comportamento serial
• Baixo overhead: escalabilidade p/ muitos núcleos
• Reducers: + rápidos do que locks,
semântica do código serial
10. O que o Intel® Cilk™ Plus NÃO É
Não é uma solução completa para multithreading
Solução completa: Intel® Threading Building Blocks
Não é uma solução de paralelismo de cluster entre
diversos nós
Solucão: Intel® Cluster Studio
Não é uma ferramenta para tornar o projeto de aplicações
paralelas mais simples
Solução: Intel® Parallel Advisor
12. Notação de Arrays - Intel® Cilk™ Plus
Sintaxe para especificar seções dos arrays nas quais executar
determinadas operações
Sintaxe: [<limite inferior> : <tamanho> : <passo>]
• Exemplos
a[0:N] = b[0:N] * c[0:N];
a[:] = b[:] * c[:] // se a, b, c são declarados
com tamanho N
A vetorização automática do compilador C++ Intel® pode usar
essa informação para aplicar operações únicas para múltiplos
elementos do array usando Intel® Streaming SIMD Extensions
(Intel® SSE) e Intel® Advanced Vector Extensions (Intel® AVX)
• Exemplo mais avançado:
x[0:10:10] = sin(y[20:10:2]);
13. Exemplo de Notação de Arrays
void foo(double * a, double * b, double * c, double * d,
double * e, int n) {
for(int i = 0; i < n; i++)
a[i] *= (b[i] - d[i]) * (c[i] + e[i]);
}
void goo(double * a, double * b, double * c, double * d,
double * e, int n) {
a[0:n] *= (b[0:n] - d[0:n]) * (c[0:n] + e[0:n]);
}
icl -Qvec-report3 -c test-array-notations.cpp
Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build
20120410
Copyright (C) 1985-2012 Intel Corporation. All rights reserved.
test-array-notations.cpp
test-array-notations.cpp(2): (col. 2) remark: loop was not vectorized: existence of vector dependence.
test-array-notations.cpp(3): (col. 3) remark: vector dependence: assumed FLOW dependence between a
line 3 and e line 3.
<snip>
test-array-notations.cpp(7): (col. 6) remark: LOOP WAS VECTORIZED.
15. Quais loops podem ser vetorizados?
Contável
Contador constante durante o loop
Entradas e Saídas Únicas
Saída do loop não pode ser dependente de dados
(deve ser baseada no contador)
Código “straight-line”
Instruções SIMD são iguais para diversas iterações do
loop. Não pode haver “branching”
O mais interno de loops encadeados
Sem chamadas de funções
Somente funções matemáticas intrínsecas ou inlines
http://d3f8ykwhia686p.cloudfront.net/1live/intel/CompilerAutovectorizationGuide.pdf
17. Funções Elementares no Intel® Cilk™ Plus
• O compilador não pode assumir que uma função definida
pelo usuário é segura para vetorização
• É possível tornar uma função “elementar”: indicar ao
compilador que a função pode ser aplicada a múltiplos
elementos de um array em paralelo de forma segura
• Utilize __declspec(vector) na declaração *E* na definição
da função, pois isso afetará o name-mangling
• Ao usar cláusulas disponíveis para ajudar diretamente o
compilador na geração do código, consulte a
documentação para detalhes
18. Exemplo de Função Elementar
double user_function(double x);
__declspec(vector) double elemental_function(double x);
double a[100];
double b[100];
void foo() {
a[:] = user_function(b[:]);
a[:] = elemental_function(b[:]);
}
icl /Qvec-report3 /c test-elemental-functions.cpp
Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build
20120410
Copyright (C) 1985-2012 Intel Corporation. All rights reserved.
test-elemental-functions.cpp
test-elemental-functions.cpp(9)
: (col. 4) remark: LOOP WAS VECTORIZED.
test-elemental-functions.cpp(8)
: (col. 4) remark: loop was not vectorized: nonstandard loop is not a vectorization candidate.
19. Obstáculos para Vetorização
Acesso não-contíguo à memória
"vectorization possible but seems inefficient“
Endereçamento indireto (3o exemplo):
“Existence of vector dependence”
20. Obstáculos para Vetorização
Dependência de Dados
No segundo caso, se não houver dependência
(aliasing), o uso de #pragma ivdep permite
“forçar” a vetorização
22. Palavras-chave do Intel® Cilk™ Plus
Cilk Plus adiciona 3 palavras-chave ao C/C++:
_cilk_spawn
_cilk_sync
_cilk_for
Usando #include <cilk/cilk.h>, você pode usar as
palavras-chave: cilk_spawn, cilk_sync e cilk_for.
O runtime do CILK Plus controla a criação de threads e seu
agendamento. O pool de threads é criado antes do uso das
palavras-chave do CILK Plus.
Por default, o número de threads é igual ao número de
núcleos (incluindo hyperthreads), mas pode ser controlado
pelo usuário
23. cilk_spawn e cilk_sync
cilk_spawn dá ao runtime a
permissão para rodar uma função-filha de forma assíncrona.
– Não é criada (nem necessária) uma 2a thread!
– Se não houver workers disponíveis, a função-filha será
executada com uma chamada a uma função serial.
– O scheduler pode “roubar” a fila da função-pai e executá-la
em paralelo com a função-filha.
– A função-pai não tem garantia de rodar em paralelo com a
função-filha.
cilk_sync aguarda a conclusão de todas as funções-filhas
antes que a execução prossiga além daquele ponto.
– Existem pontos de sincronismo (cilk_sync) implícitos
24. Um exemplo simples
Computação recursiva do número de Fibonacci:
int fib(int n)
{
int x, y;
if (n < 2) return n;
x = cilk_spawn fib(n-1);
y = fib(n-2);
cilk_sync;
return x+y;
}
Chamadas assíncronas devem
completar antes de usar x.
Execução pode continuar
enquanto fib(n-1) roda.
25. cilk_for
Semelhante a um loop “for” regular.
cilk_for (int x = 0; x < 1000000; ++x) { … }
Qualquer iteração pode executar em paralelo com qualquer
outra.
Todas as interações completam antes do programa prosseguir.
Limitações:
– Limitado a uma única variável de controle.
– Deve ser capaz de voltar ao início de qualquer iteração,
randomicamente.
– Iterações devem ser independentes umas das outras.
26. Nos bastidores do cilk_for…
void run_loop(first, last) {
if ((last - first) < grainsize) {
for (int i=first; i<last ++i)
{LOOP_BODY;}
}
else {
int mid = (last-first)/2;
cilk_spawn run_loop(first, mid);
run_loop(mid, last);
}
}
27. Exemplos de cilk_for
cilk_for (int x; x < 1000000; x += 2) { … }
cilk_for (vector<int>::iterator x =
y.begin();
x != y.end(); ++x) { … }
cilk_for (list<int>::iterator x = y.begin();
x != y.end(); ++x) { … }
O contador do loop não pode ser calculado em tempo de
compilação usando uma lista.
(y.end() – y.begin() não é definido)
Não há acesso randômico aos elementos de uma lista.
(y.begin() + n não é definido.)
28. Serialização
Todo programa Cilk Plus tem um equivalente serial,
chamado de serialização
A serialização é obtida removendo as palavras-chave
cilk_spawn e cilk_sync e substituindo
cilk_for por for
O compilador produzirá a serialização se você
compilar com /Qcilk-serialize (Windows*) ou
–cilk-serialize (Linux*/OS X*)
Rodar um programa com somente um worker é
equivalente a rodar a serialização.
29. Semântica Serial
Um programa CILK Plus determinístico terá a mesma
semântica se sua serialização.
– Facilita a realização de testes de regressão;
– Facilita o debug:
– Roda com somente um núcleo
– Roda serializado
– Permite composição
– Vantagens dos hyperobjects
– Ferramentas de análise robustas (Cilk Plus SDK)
– cilkscreen race detector
– cilkview scalability analyzer
30. Sincronismos implícitos
void f() {
cilk_spawn g();
cilk_for (int x = 0; x < lots; ++x) {
...
}
try {
cilk_spawn h();
}
catch (...) {
...
}
} Ao final de uma funcão utilizando spawn
Ao final do corpo de um cilk_for (não sincroniza g())
Ao final de um bloco try contendo um spawn
Antes de entrar num bloco try contendo um sync
31. Composição
Sincronismos implícitos são importantes para tornar
cada chamada de função uma “caixa preta”.
Quem chama a função não sabe (nem se importa) se
a função chamada implementa spawns.
A abstração serial é mantida.
Que chama a função não precisa se preocupar com data
races na função chamada.
cilk_sync sincroniza somente funções-filhas que
foram “spawned” dentro da mesma função do sync:
nenhuma ação ocorre “à distância”.
32. Um exemplo de soma
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
int result = 0;
for (std::size_t i = 0; i < n; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
33. Somando com Intel® Cilk™ Plus
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
int result = 0;
cilk_for (std::size_t i = 0; i < n; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
Race!
34. Solução com Locks
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
mutex L;
int result = 0;
cilk_for (std::size_t i = 0; i < n; ++i)
{
int temp = compute(myArray[i]);
L.lock();
result += temp;
L.unlock();
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
Problemas
Sobrecarga e
contenção dos
Locks
35. Solução com Reducer do CILK™ Plus
int compute(const X& v);
int main()
{
const std::size_t ARRAY_SIZE = 1000000;
extern X myArray[ARRAY_SIZE];
// ...
cilk::reducer_opadd<int> result;
cilk_for (std::size_t i = 0; i < ARRAY_SIZE; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result.get_value()
<< std::endl;
return 0;
}
Declare result como
reducer de soma (int)
Atualizações são
resolvidas automatica/e,
sem races nem contenção
Ao final, o valor (int) pode
ser recuperado (soma)
36. Biblioteca de “HyperObjects”
A biblioteca de hyperobjects do Intel® Cilk™ Plus’s contém os
“reducers” mais utilizados (e mais) :
– reducer_list_append
– reducer_list_prepend
– reducer_max
– reducer_max_index
– reducer_min
– reducer_min_index
– reducer_opadd
– reducer_ostream
– reducer_basic_string
– holder
– …
Você pode escrever seu próprio reducer usando
cilk::monoid_base e cilk::reducer.
37. Use o Intel® Cilk™ Plus
Disponível em:
Intel® C++ Composer XE 2011
– Incluído no Intel® Parallel Studio XE 2011 SP1
– Avaliação gratuita (30 dias) em
http://software.intel.com/en-us/articles/intel-
software-evaluation-center/
Patch do gcc* 4.7 (Open Source)
– Obtenha em: http://cilk.com
38. Material complementar
Sobre Intel® Cilk™ Plus
http://cilk.com
Intel® Threading Building Blocks
http://threadingbuildingblocks.org
Suporte
http://premier.intel.com
Fóruns de usuários
http://software.intel.com/pt-br/forums
http://software.intel.com/en-us/forums/intel-cilk-plus
Apresentações técnicas
http://software.intel.com/en-us/articles/intel-software-
development-products-technical-presentations/
(incluem mais detalhes do Cilk Plus, vetorização, Intel® Cluster
Studio e muito mais!)
41. Risk Factors
The above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-looking
statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,”
“will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions
also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors
could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the
important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due
to factors including changes in business and economic conditions, including supply constraints and other disruptions affecting customers; customer acceptance of
Intel’s and competitors’ products; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers.
Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events,
which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high
percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the
gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken
by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s
ability to respond quickly to technological developments and to incorporate new features into its products. Intel is in the process of transitioning to its next
generation of products on 22nm process technology, and there could be execution and timing issues associated with these changes, including products defects
and errata and lower than anticipated manufacturing yields. The gross margin percentage could vary significantly from expectations based on capacity utilization;
variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the
timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions
in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and
intangible assets. The majority of Intel’s non-marketable equity investment portfolio balance is concentrated in companies in the flash memory market segment,
and declines in this market segment or changes in management’s plans with respect to Intel’s investments in this market segment could result in significant
impairment charges, impacting restructuring charges as well as gains/losses on equity investments and interest and other. Intel's results could be affected by
adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict
and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain
marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and
the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by
adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving
intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports.
An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular
business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed
discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the report on Form 10-K for the year ended Dec.
31, 2011.
Rev. 4/17/12