我需要多核编程方面的帮助 [英] I need help in multi-core programing

查看:75
本文介绍了我需要多核编程方面的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写多核程序,并且需要帮助.
例如,如果我要为双核编写此脚本,它的外观如何?

I would like to write multi-core program, and I need help.
for example if I would write this script for dual core, how would it look like?

#include <stdio.h>
int main()
{
int j,i,x,y;
x=2;
y=3;
for (i = 0; i <10; i++) x*=x;    //calculating first core
for (j = 0; j <10; j++) y*=y;    //calculating second core
return 0;
}



请帮助我!



Help me, please!

推荐答案

单句无法回答.基本上,这只是让程序中的每个任务在单独的线程中运行的问题.

设置线程是一项繁琐的工作,并且要同步共享数据的访问,避免死锁或类似的陷阱可能变得非常复杂.至少如果您超出了示例范围.

也许这里的这篇文章可以帮助您上路: http://www.codeproject.com/KB/threads /MultithreadingTutorial.aspx [ ^ ]
That cannot be answered in a single sentence. Basically it is ''just'' a matter of letting each task in your program run in a separate thread.

Setting up the threads is a little work and synchronizing the access of shared data, avoiding deadlocks or similar pitfalls can become be extremely complex. At least if you go beyond your example.

Perhaps this article here will help you to get on the road: http://www.codeproject.com/KB/threads/MultithreadingTutorial.aspx[^]


这是一个简单的示例. (实际上并未使用Thread_1和Thread_2方法)

Here a simple example. (methods Thread_1 and Thread_2 aren''t actually used)

#include <windows.h> <windows.h>
#include <strsafe.h> <strsafe.h>
#include <stdio.h><stdio.h>

// Define the two methods
DWORD WINAPI Thread_1( LPVOID lpParam ) 
{
  int i,x;
  x=2;
  for (i = 0; i <10; i++) x*=x;    //calculating first core
  return 0; 
} 

DWORD WINAPI Thread_2( LPVOID lpParam ) 
{
  int j,y;
  y=3;
  for (j = 0; j <10; j++) y*=y;    //calculating second core
  return 0;
} 

// Or since they do practically the same, just a single method and pass the multiplier value as lpParaml
DWORD WINAPI Thread_proc( LPVOID lpParam ) 
{
  int x = *((int*)lpParam); 
  int i;
  for (i = 0; i <10; i++) x*=x;    //calculating first core
  return 0; 
} 

int main()
{
  HANDLE thread_handle_array[2];
  int thread_data = 2;
  thread_handle_array[0] = CreateThread( NULL, 0, Thread_proc, &thread_data, 0, NULL);  
  if ( thread_handle_array[0] == NULL) ExitProcess(thread_handle_array[0]);

  thread_data = 3;
  thread_handle_array[1] = CreateThread( NULL, 0, Thread_proc, &thread_data, 0, NULL);  
  if ( thread_handle_array[0] == NULL) ExitProcess(thread_handle_array[1]);

  WaitForMultipleObjects( 2, thread_handle_array, TRUE, INFINITE);
  // If creation of the thread failed, this will only give an exception under a debugger.
  CloseHandle(thread_handle_array[1]);
  CloseHandle(thread_handle_array[1]);
}



祝你好运!



Good luck!


这篇关于我需要多核编程方面的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆