0
爲什麼我在嘗試將std::mutex mtx
置於對象內時出現錯誤?當它被宣佈爲全球性時,沒有錯誤。我的語法有什麼問題嗎?聲明爲私有成員的互斥鎖會生成一個錯誤,但不會生成全局錯誤
錯誤說:
std::tuple<void (__thiscall XHuman::*)(int),XHuman,int>::tuple(std::tuple<void (__thiscall XHuman::*)(int),XHuman,int> &&)': cannot convert argument 1 from 'void (__thiscall XHuman::*)(int)' to 'std::allocator_arg_t
std::tuple<void (__thiscall XHuman::*)(int,int),XHuman,int,int>::tuple': no overloaded function takes 4 arguments
這是我的代碼
#include "stdafx.h"
#include <vector>
#include <Windows.h>
#include <thread>
#include <mutex>
class XHuman
{
private:
std::vector<int> m_coordinates;
std::mutex mtx;
public:
XHuman() {
printf("Initialized XHuman\n");
for (int i = 0; i < 5; ++i){
m_coordinates.push_back(i);
}
}
std::vector<int> Coordinates() { return m_coordinates; }
void operator()() {
printf("hello\n");
}
void addValues(int val, int multiple)
{
std::lock_guard<std::mutex> guard(mtx);
for (int i = 0; i < multiple; ++i){
m_coordinates.push_back(val);
printf("pushed_back %d\n", val);
Sleep(100);
}
printf("m_coordinates.size() = %d\n", m_coordinates.size());
}
void eraseValues(int multiple)
{
std::lock_guard<std::mutex> guard(mtx);
for (int i = 0; i < multiple; ++i) {
m_coordinates.pop_back();
printf("m_coordinates.size() = %d\n", m_coordinates.size());
}
}
};
int main()
{
std::thread th1(&XHuman::addValues, XHuman(), 1, 5);
std::thread th2(&XHuman::eraseValues, XHuman(), 1);
th1.join();
th2.join();
return 0;
}
您可能想要爲兩個線程使用'XHuman'的相同實例,否則這裏沒有太多用處。請參閱@Praetorian答案,只需將'&one'傳遞給兩個線程。 – Holt