同时运行两个功能 [英] Run two functions at the same time
本文介绍了同时运行两个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个职能.我如何同时运行两个功能?我知道应该使用线程.我需要一个多线程示例.我正在使用Visual Studio 2010
I have two functions. How would i run two functions at the same time? I Know should use threading. I need a example for Multi Threading . I am using Visual Studio 2010
推荐答案
您可以使用 _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;
}
如果您可以使用C ++ 11,则可以使用 std :: thread:
If you've got access to C++11 you can use std::thread :
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;
}
And, if you want to get down to the metal you can use the 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;
}
这篇关于同时运行两个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文