如果你不想设计过多底层的线程操作,那就选择一个并发开发平台,由平台来自动协调,调度和管理多核资源。并发开发平台包括各种线程池的库,例如
.NET的ThreadPool类
Java的Concurrent类
消息传递环境,例如MPI
data-parallel编程环境,例如NESL, RapidMind, ZPL
task-parallel编程环境, 例如Intel的Threading Building Blocks (TBB) 和 Microsoft的Task Parallel Library (TPL)
动态编程环境,例如Cilk or Cilk++或者业界标准OpenMP.
这些并发平台通过提供语言抽象,扩充注释或者提供库函数的方式来支持多核开发。
程序的性能 (使用多核就是为了提升程序的性能的)
开发的时间
程序的可靠性
代码简洁:直接使用底层线程库操作代码是十分复杂的
模块化:直接使用底层线程库操作还会破坏代码的模块化
单核时代,我们写Fibonacci代码的方法如下:
- int fib(int n)
- {
- if (n < 2) return n;
- else {
- int x = fib(n-1);
- int y = fib(n-2);
- return x + y;
- }
- }
- int main(int argc, char *argv[])
- {
- int n = atoi(argv[1]);
- int result = fib(n);
- printf("Fibonacci of %d is %d.\n", n, result);
- return 0;
- }
- int fib(int n)
- {
- if (n < 2) return n;
- else {
- int x = fib(n-1);
- int y = fib(n-2);
- return x + y;
- }
- }
- typedef struct {
- int input;
- int output;
- } thread_args;
- void *thread_func ( void *ptr )
- {
- int i = ((thread_args *) ptr)->input;
- ((thread_args *) ptr)->output = fib(i);
- return NULL;
- }
- int main(int argc, char *argv[])
- {
- pthread_t thread;
- thread_args args;
- int status;
- int result;
- int thread_result;
- if (argc < 2) return 1;
- int n = atoi(argv[1]);
- if (n < 30) result = fib(n);
- else {
- args.input = n-1;
- status = pthread_create(thread,
- NULL, thread_func,
- (void*) &args );
- // main can continue executing while the thread executes.
- result = fib(n-2);
- // Wait for the thread to terminate.
- pthread_join(thread, NULL);
- result += args.output;
- }
- printf("Fibonacci of %d is %d.\n", n, result);
- return 0;
- }
使用OpenMP
- int fib(int n) {
- int i, j;
- if (n<2)
- return n;
- else {
- #pragma omp task shared(i)
- i=fib(n-1);
- #pragma omp task shared(j)
- j=fib(n-2);
- #pragma omp taskwait
- return i+j;
- }
- }
- int fib(int n)
- {
- if (n < 2) return n;
- else {
- int x = cilk_spawn fib(n-1);
- int y = fib(n-2);
- cilk_sync;
- return x + y;
- }
- }
- int main(int argc, char *argv[])
- {
- int n = atoi(argv[1]);
- int result = fib(n);
- printf("Fibonacci of %d is %d.\n", n, result);
- return 0;
- }
- Private Function FiboFullParallel(ByVal N As Long) As Long
- If N <= 0 Then Return 0
- If N = 1 Then Return 1
- Dim t1 As Tasks.Future(Of Long) = Tasks.Future(Of Long).Create( Function() FiboFullParallel(N - 1))
- Dim t2 As Tasks.Future(Of Long) = Tasks.Future(Of Long).Create( Function() FiboFullParallel(N - 2))
- Return t1.Value + t2.Value
- End Function
五、什么情况下该使用多核编程呢?
- #pragma omp parallel for if(n > 100000)
- for (i = 0; i < n;, i++) {
- ...
- }