Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 threads with shared mutex and class instance

Hello I am experimenting with C++11 and threads. I am facing some problems I can't figure out how to solve. I want to do stuff of a class in another thread and need to use a mutex in several functions and the class. Yes I know std::mutex is not copyable but I do not know how to solve my problem.

What I have so far is main.cpp:

#include <iostream>
#include <thread>
#include <mutex>
#include "ThreadClass.h"

void thread_without_class(std::mutex &mutex);
void thread_without_class2(int number, std::mutex &mutex);

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

ThreadClass *threadClass = new ThreadClass();

std::thread t1(thread_without_class, &mutex);
std::thread t2(thread_without_class2, 10, &mutex);
std::thread t3(thread_without_class2, 11, &mutex);
std::thread t4(threadClass);

threadClass->mutex = mutex;
threadClass->numberOfOutputsI = 5;
threadClass->ThreadOutput();

t1.join();
t2.join();
t3.join();
t4.join();

delete threadClass;
return 0;
}


void thread_without_class(std::mutex &mutex){
std::lock_guard<std::mutex> lock(mutex);
std::cout << "c++11 thread without anything" << std::endl;
}

void thread_without_class2(int number, std::mutex &mutex){
for (auto i=0; i<number; i++){
    std::lock_guard<std::mutex> lock(mutex);
    std::cout << "c++11 thread with function parameter: " << number << std::endl;
}
}

ThreadClass.h:

#pragma once
#include <mutex>

class ThreadClass{
public:
ThreadClass(void);
~ThreadClass(void);
void ThreadOutput();

std::mutex mutex;
int numberOfOutputsI;
};

ThreadClass.cpp

#include "ThreadClass.h"
#include <iostream>

ThreadClass::ThreadClass(void){
numberOfOutputsI = 0;
}

ThreadClass::~ThreadClass(void){
}

void ThreadClass::ThreadOutput(){
for (auto i=0; i<numberOfOutputsI; i++){
    std::lock_guard<std::mutex> lock(mutex);
    std::cout << "I am a class called as a thread" << std::endl;
}}
like image 532
akira hinoshiro Avatar asked Sep 01 '26 14:09

akira hinoshiro


1 Answers

You don't want copy, but a reference/pointer:

class ThreadClass{
    //..
    std::mutex* mutex = nullptr;
};

And in main:

threadClass->mutex = &mutex;
like image 88
Jarod42 Avatar answered Sep 04 '26 21:09

Jarod42