我试图用C++(Win32)创建一个线程来运行一个简单的方法.我是C++线程的新手,但对C#中的线程非常熟悉.这是我正在尝试做的一些伪代码:
static void MyMethod(int data) { RunStuff(data); } void RunStuff(int data) { //long running operation here }
我想从MyMethod调用RunStuff而不阻塞它.在单独的线程上运行RunStuff最简单的方法是什么?
编辑:我还应该提一下,我希望将依赖关系保持在最低限度.(没有MFC ......等)
#includestatic boost::thread runStuffThread; static void MyMethod(int data) { runStuffThread = boost::thread(boost::bind(RunStuff, data)); } // elsewhere... runStuffThread.join(); //blocks
C++ 11可与更新的编译器(如Visual Studio 2013)一起使用,其中包含线程作为语言的一部分以及其他一些非常好的部分,例如lambda.
include文件threads
提供了一个线程类,它是一组模板.线程功能在std::
命名空间中.一些线程同步函数std::this_thread
用作命名空间(请参阅为什么std :: this_thread命名空间?以获得一些解释).
使用Visual Studio 2013的以下控制台应用程序示例演示了C++ 11的一些线程功能,包括使用lambda(请参阅C++ 11中的什么是lambda表达式?).请注意,用于线程休眠的函数(例如std::this_thread::sleep_for()
,使用持续时间来自)std::chrono
.
// threading.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include#include #include #include int funThread(const char *pName, const int nTimes, std::mutex *myMutex) { // loop the specified number of times each time waiting a second. // we are using this mutex, which is shared by the threads to // synchronize and allow only one thread at a time to to output. for (int i = 0; i < nTimes; i++) { myMutex->lock(); std::cout << "thread " << pName << " i = " << i << std::endl; // delay this thread that is running for a second. // the this_thread construct allows us access to several different // functions such as sleep_for() and yield(). we do the sleep // before doing the unlock() to demo how the lock/unlock works. std::this_thread::sleep_for(std::chrono::seconds(1)); myMutex->unlock(); std::this_thread::yield(); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { // create a mutex which we are going to use to synchronize output // between the two threads. std::mutex myMutex; // create and start two threads each with a different name and a // different number of iterations. we provide the mutex we are using // to synchronize the two threads. std::thread myThread1(funThread, "one", 5, &myMutex); std::thread myThread2(funThread, "two", 15, &myMutex); // wait for our two threads to finish. myThread1.join(); myThread2.join(); auto fun = [](int x) {for (int i = 0; i < x; i++) { std::cout << "lambda thread " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } }; // create a thread from the lambda above requesting three iterations. std::thread xThread(fun, 3); xThread.join(); return 0; }