且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我需要多核编程方面的帮助

更新时间:2023-02-26 14:23:19

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

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

也许这里的这篇文章可以帮助您上路: 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!