Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is passing mutex to thread not possible?

Passing a mutex reference to a thread causes compile errors. Why is it not possible (I have multiple threads using the same shared variable), and how do I fix it?

#include<iostream>
#include<thread>
#include<mutex>

void myf(std::mutex& mtx)
{
    while(true)
    {
        // lock 
        // do something
        // unlock
    }
}


int main(int argc, char** argv) 
{
    std::mutex mtx;

    std::thread t(myf, mtx);

    t.join(); 
    return 0; 
}
like image 214
Bob Avatar asked Jul 09 '15 03:07

Bob


1 Answers

thread copies its arguments:

First the constructor copies/moves all arguments...

std::mutex is not copyable, hence the errors. If you want to pass it by reference, you need to use std::ref:

std::thread t(myf, std::ref(mtx));

Demo

like image 124
Barry Avatar answered Oct 21 '22 15:10

Barry