2017-08-16 42 views
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; 
} 
+0

您可能想要爲兩個線程使用'XHuman'的相同實例,否則這裏沒有太多用處。請參閱@Praetorian答案,只需將'&one'傳遞給兩個線程。 – Holt

回答

4

std::threadconstructor複製或移動它的參數。 std::mutex既不可複製也不可移動,因此將其包括爲XHuman的非靜態數據成員會使該類不可複製且不可移動。這是你看到的錯誤的原因。

您可以通過將指針或參考傳遞給XHuman實例來繞過它。

XHuman one, two; 
std::thread th1(&XHuman::addValues, &one, 1, 5); 
std::thread th2(&XHuman::eraseValues, std::ref(two), 1); 
+0

只是我需要的正確答案。謝謝! – Gibs