我发现很多关于在类中创建新线程(将成员函数传递给std :: thread)
但是在某种程度上可以做到以下几点:
#include <iostream>
#include <thread>
using namespace std;
class myClass
{
public:
myClass(){
myInt = 2;
};
void myFun(){
++myInt;
}
int ret_myInt(){
return myInt;
}
private:
int myInt;
};
int main ( void )
{
myClass myObj_;
std::thread t1( myObj_.myFun ); // (1)
t1.join();
cout << myObj_.ret_myInt() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码不起作用,因为我不能在这里调用成员函数(1).有一个简单的方法吗?
要明确:我不想在成员函数中创建线程.
我有一个atomic< int > position;,我想在同一个线程中增加一个:
void increasePosition()
{
int temp;
temp = position.load( memory_order_consume );
position.store( ++temp, memory_order_release );
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做,还是我犯了错误?内存排序是否正确?