Bob
Bob

Reputation: 483

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; 
}

Upvotes: 16

Views: 8679

Answers (1)

Barry
Barry

Reputation: 303897

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

Upvotes: 26

Related Questions