具有共享互斥锁和类实例的C ++ 11线程 [英] C++11 threads with shared mutex and class instance

查看:118
本文介绍了具有共享互斥锁和类实例的C ++ 11线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在尝试C ++ 11和线程。我遇到了一些我无法解决的问题。我想在另一个线程中做一个类的事情,并且需要在多个函数和该类中使用互斥体。
是的,我知道std :: mutex无法复制,但我不知道如何解决我的问题。

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.

到目前为止,我所拥有的是
main.cpp:

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:

ThreadClass.h:

#pragma once
#include <mutex>

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

std::mutex mutex;
int numberOfOutputsI;
};

ThreadClass.cpp

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


推荐答案

您不想要复制,但是引用/指针:

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

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

main 中:

threadClass->mutex = &mutex;

这篇关于具有共享互斥锁和类实例的C ++ 11线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆