2014-02-09 3 views
0

두 가지 기능이 있습니다. 어떻게 동시에 두 개의 함수를 실행할 수 있습니까? 나는 스레딩을 사용해야합니다. 멀티 스레딩의 예가 필요합니다. 당신이 원하는 경우,동시에 두 기능 실행

void CalculatePrimes() 
{ 
    // Do something 
} 

void TransmitFile() 
{ 
    // Do domething 
} 

int main() 
{ 
    std::thread x(CalculatePrices); 
    std::thread y(TransmitFile); 

    // Both function are now running an different thread 
    // We need to wait for them to finish 

    x.join(); 
    y.join(); 

    return 0; 
} 

그리고 : 당신은 당신이 std::thread를 사용할 수있는 C++ (11)에 대한 액세스 권한을 가지고있는 경우에 I 2010

답변

2

당신은 _beginthread

void CalculatePrimes(void*) 
{ 
    // Do something 
} 

void TransmitFile(void*) 
{ 
    // Do domething 
} 

int main() 
{ 
    uintptr_ x = _beginthread(CalculatePrices,0,NULL); 
    uintptr_ y = _beginthread(TransmitFile,0,NULL); 

    return 0; 
} 

를 사용할 수있는 비주얼 스튜디오를 사용하고 당신은 금속을 얻을 수 CreateThread API를 사용할 수 있습니다 :

DWORD WINAPI CalculatePrimes(void *) 
{ 
    // Do something 
    return 0; 
} 

DWORD WINAPI TransmitFile(void *) 
{ 
    // Do something 
    return 0; 
} 

int main() 
{ 
    HANDLE x=::CreateThread(NULL,0,CalculatePrimes,NULL,0,NULL); 
    HANDLE y=::CreateThread(NULL,0,CalculatePrimes,NULL,0,NULL); 

    // Wait for them to finish 
    ::WaitForSingleObject(x,INFINITE); 
    ::WaitForSingleObject(y,INFINITE); 

    return 0; 
} 
1

당신이 사용하는 경우 MSDN for AfxBeginThread을 참조하십시오

UINT SomeFunction(LPVOID pParam) 
{ 
    CSomeObject * pObject = (CSomeObject*)pParam; 

    // do stuff 

    return 0; // thread completed successfully 
} 

int main() 
{ 
    CSomeObject pObject = new CSomeObject; 
    AfxBeginThread(SomeFunction, pObject); 

    ... 

    return 0; 
} 

: MFC, 당신은 CWinThread을 만들 AfxBeginThread를 사용할 수 있습니다.

+2

당신은, 내가 실수로 내가 "비주얼 스튜디오 2010을 사용"읽을 때 그 사건이었다 가정 AfxBeginThread' – Sean

+1

@Sean 진정한'호출하는 MFC 응용 프로그램을 작성해야합니다. 답변을 편집하여 MFC를 언급했습니다. – schumacher574

1

< 스레드에 대한 MSDN 참조>는 VS2010이 아니라 VS2012로 돌아갑니다. 당신은 VS2012로 업데이트 할 수 있습니다 (Win 7 또는 Win 8을 실행해야합니다). 다음은 두 개의 스레드를 사용하여 파일을 복사하는 C로 작성된 Windows 콘솔 프로그램의 압축에 대한 링크입니다. 윈도우 뮤텍스와 세마포어를 사용하여 스레드 간 단일 링크 목록 메시징 인터페이스를 구현합니다.

mtcopy.zip