gpt4 book ai didi

具有共享互斥锁和类实例的 C++11 线程

转载 作者:行者123 更新时间:2023-11-30 01:44:17 25 4
gpt4 key购买 nike

您好,我正在试验 C++11 和线程。我面临着一些我不知道如何解决的问题。我想在另一个线程中做一个类的事情,需要在几个函数和类中使用互斥锁。是的,我知道 std::mutex 不可复制,但我不知道如何解决我的问题。

到目前为止我所拥有的是 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;
}
}

线程类.h:

#pragma once
#include <mutex>

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

std::mutex mutex;
int numberOfOutputsI;
};

线程类.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;
}}

最佳答案

你不需要复制,而是一个引用/指针:

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

main 中:

threadClass->mutex = &mutex;

关于具有共享互斥锁和类实例的 C++11 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36471955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com