연습: 간단한 작업을 사용하기 위해 기존 코드 조정

이 항목에서는 Windows API를 사용하는 기존 코드를 조정하여 간단한 작업을 사용하기 위해 스레드를 만들고 실행하는 방법을 보여 줍니다.

간단한 작업은 동시성::Scheduler 또는 동시성::ScheduleGroup 개체에서 직접 예약하는 작업입니다. 간단한 작업은 동시성 런타임의 일정 예약 기능을 사용하도록 기존 코드를 조정하는 경우에 유용합니다.

필수 조건

이 연습을 시작하기 전에 작업 스케줄러 항목을 읽어 보세요.

예시

다음 예제에서는 스레드를 만들고 실행하기 위해 Windows API를 일반적으로 사용하는 방법을 보여 줍니다. 이 예제에서는 CreateThread 함수를 사용하여 별도의 스레드에서 호출합니다MyThreadFunction.

초기 코드

// windows-threads.cpp
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define BUF_SIZE 255

DWORD WINAPI MyThreadFunction(LPVOID param);

// Data structure for threads to use.
typedef struct MyData {
    int val1;
    int val2;
} MYDATA, *PMYDATA;

int _tmain()
{
   // Allocate memory for thread data.
   PMYDATA pData = (PMYDATA) HeapAlloc(GetProcessHeap(), 
      HEAP_ZERO_MEMORY, sizeof(MYDATA));

   if( pData == NULL )
   {
      ExitProcess(2);
   }

   // Set the values of the thread data.
   pData->val1 = 50;
   pData->val2 = 100;

   // Create the thread to begin execution on its own.
   DWORD dwThreadId;
   HANDLE hThread = CreateThread( 
      NULL,                   // default security attributes
      0,                      // use default stack size  
      MyThreadFunction,       // thread function name
      pData,                  // argument to thread function 
      0,                      // use default creation flags 
      &dwThreadId);           // returns the thread identifier 

   if (hThread == NULL) 
   {      
      ExitProcess(3);
   }

   // Wait for the thread to finish.
   WaitForSingleObject(hThread, INFINITE);

   // Close the thread handle and free memory allocation.
   CloseHandle(hThread);
   HeapFree(GetProcessHeap(), 0, pData);

   return 0;
}

DWORD WINAPI MyThreadFunction(LPVOID lpParam)
{
   PMYDATA pData = (PMYDATA)lpParam;

   // Use thread-safe functions to print the parameter values.

   TCHAR msgBuf[BUF_SIZE];
   StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"), 
     pData->val1, pData->val2); 

   size_t cchStringSize;
   StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);

   DWORD dwChars;
   WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), msgBuf, (DWORD)cchStringSize, &dwChars, NULL);

   return 0;
}

이 예제의 결과는 다음과 같습니다.

Parameters = 50, 100

다음 단계에서는 동시성 런타임을 사용하여 동일한 작업을 수행하도록 코드 예제를 조정하는 방법을 보여줍니다.

간단한 작업을 사용하도록 예제를 조정하려면

  1. #include 헤더 파일 concrt.h에 대한 지시문을 추가합니다.
#include <concrt.h>
  1. 네임스페이 usingconcurrency 스에 대한 지시문을 추가합니다.
using namespace concurrency;
  1. 호출 규칙을 사용하고 __cdecl 반환void할 선언 MyThreadFunction 을 변경합니다.
void __cdecl MyThreadFunction(LPVOID param);
  1. 태스크가 MyData 완료되었음을 기본 애플리케이션에 신호를 주는 동시성::event 개체를 포함하도록 구조를 수정합니다.
typedef struct MyData {
    int val1;
    int val2;
    event signal;
} MYDATA, *PMYDATA;
  1. 호출을 CreateThread 동시성::CurrentScheduler::ScheduleTask 메서드에 대한 호출로 바꿉다.
CurrentScheduler::ScheduleTask(MyThreadFunction, pData);
  1. 호출을 WaitForSingleObject 동시성::event::wait 메서드에 대한 호출 로 바꿔 작업이 완료될 때까지 기다립니다 .
// Wait for the task to finish.
pData->signal.wait();
  1. 에 대한 호출을 제거합니다 CloseHandle.

  2. 정의 MyThreadFunction 의 서명을 3단계와 일치하도록 변경합니다.

void __cdecl MyThreadFunction(LPVOID lpParam)
  1. 함수의 MyThreadFunction 끝에서 동시성::event::set 메서드를 호출하여 작업이 완료되었음을 기본 애플리케이션에 신호를 표시합니다.
pData->signal.set();
  1. 에서 returnMyThreadFunction문을 제거합니다.

완료된 코드

다음 완성된 예제에서는 간단한 작업을 사용하여 함수를 호출하는 코드를 보여 주는 MyThreadFunction 예제입니다.

// migration-lwt.cpp
// compile with: /EHsc
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <concrt.h>

using namespace concurrency;

#define BUF_SIZE 255

void __cdecl MyThreadFunction(LPVOID param);

// Data structure for threads to use.
typedef struct MyData {
    int val1;
    int val2;
    event signal;
} MYDATA, *PMYDATA;

int _tmain()
{
   // Allocate memory for thread data.
   PMYDATA pData = (PMYDATA) HeapAlloc(GetProcessHeap(), 
      HEAP_ZERO_MEMORY, sizeof(MYDATA));

   if( pData == NULL )
   {
      ExitProcess(2);
   }

   // Set the values of the thread data.
   pData->val1 = 50;
   pData->val2 = 100;

   // Create the thread to begin execution on its own.
   CurrentScheduler::ScheduleTask(MyThreadFunction, pData);

   // Wait for the task to finish.
   pData->signal.wait();

   // Free memory allocation.
   HeapFree(GetProcessHeap(), 0, pData);

   return 0;
}

void __cdecl MyThreadFunction(LPVOID lpParam)
{
   PMYDATA pData = (PMYDATA)lpParam;

   // Use thread-safe functions to print the parameter values.

   TCHAR msgBuf[BUF_SIZE];
   StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"), 
     pData->val1, pData->val2); 

   size_t cchStringSize;
   StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);

   DWORD dwChars;
   WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), msgBuf, (DWORD)cchStringSize, &dwChars, NULL);

   pData->signal.set();
}

참고 항목

작업 Scheduler
Scheduler 클래스