Cpp 并发编程小计
大都是搬运,算是参考时方便些
1.1 在类中使用 pthread,不是 static 的方法很难使用,找了个方法。可是很丑陋。
1.2 直接使用 std::thread使用 this第一次没仔细看, 发现可以直接使用类的非 static 类。话说,当初为嘛没看出来…
1.3 再进一步
用C++11的std::async代替线程的创建
1.4 C++ 多线程下的: error C3867: 使用 “&” 来创建指向成员的指针
“&” 同样适用于 async
1.5 实例程序
#include <iostream>
//#include <thread>
#include <future>
using namespace std;
class HelloWorld
{
public:
bool init();
int myThread(int first, int second);
};
bool HelloWorld::init()
{
//std::thread t1(&HelloWorld::myThread, this, 10, 20);//创建一个分支线程,回调到myThread函数里
//t1.join();
t1.detach();
std::future<int> f1 = std::async(std::launch::async, &HelloWorld::myThread, this, 1, 2);
cout << f1.get() << endl; //output: 8
printf("in major thread");//在主线程
return true;
}
int HelloWorld::myThread(int first, int second)
{
printf("in my thread,first = %d,second = %d", first, second);
return first + second;
}
int main()
{
HelloWorld hello;
hello.init();
return 0;
}
1.6 小结
使用 async 可以获得我们想要的 – 同步,且能获取返回值
1.7 还是用的太少了,出现了 “error C2064: term does not evaluate to a function taking 0 arguments” 错误。下面的代码很好的说明了出现的问题
#include <iostream>
#include <thread>
using namespace std;
int plainHello(){
cout << "hello is always ok" << endl;
return 0;
}
class Hello{
public:
Hello(){};
~Hello(){};
void say(){
cout << "hei in hello" << endl;
}
static void staticSay(){
cout << "static say is also ok" << endl;
}
};
int main()
{
thread t1(plainHello); //直接调用不会有问题
t1.join();
//thread t2(&Hello::say); //编译出错,error C2064: term does not evaluate to a function taking 0 arguments。是说没有提供类的实例
//t2.join();
Hello hello;
thread t3(&Hello::say, &hello); //提供了类的实例,可以正确找到调用的方法
t3.join();
thread t4(&Hello::staticSay); //静态方法,不提供类的实例
t4.join();
return 0;
}