c++ - 线程可以调用Class Function并访问类数据吗?

标签 c++ multithreading pthreads

对于我必须上学的项目,有人要求我使用线程编写程序。我正在使用的库是<pthread.h>。为了理解线程的工作方式,我尝试通过在空白文件中编写一些代码来查看线程的行为。实际上,我感谢另一个stackoverflow问题,如何将pthread_create()传递给类函数,它确实有效,但是现在又有另一个问题,我在任何地方都找不到答案。该程序将编译并打印与我在类中放入的整数不相符的随机整数。也许线程调用的方法无法访问类内部的数据?那是代码:

class myClass {

    public:
        myClass() {
            for(int i = 0; i < 5; i++)
                values[i] = i*3;
        }
        void myFunction() {
            
            pthread_t processIDs[5];
            int count[5];
            
            for(int i = 0; i < 5; i++) {
                count[i] = i;
                pthread_create(&processIDs[i], NULL, &printIntegerHelper, &count[i]);
            }
            for(int i = 0; i < 5; i++) {
                pthread_join(processIDs[i], NULL);
            }
        }
    private:
        void* printInteger(int index) {
            printf("%d", values[index]);
        }
        static void* printIntegerHelper(void* arg) {
            Sleep(20);
            return ((myClass *) arg)->printInteger(*((int*)arg));
        }
    protected:
        int values[5];
};
int main(void){
    
    myClass myObject;
    
    myObject.myFunction();
    
    return 0;
}

最佳答案

这里的主要问题是您试图将单个指针arg转换为指向不同无关事物的两个指针,然后取消对结果的引用。如果没有未定义的行为,您将无法做到。您只能传递一个指向pthread_create()的指针,并且如果您需要传递更多的指针(例如,指针+索引),则需要一个附加的间接方式:将您的信息包装到struct(或std::pair/std::tuple)中,然后将指针传递给它。这就是std::thread在内部执行的操作。
简单的例子:

using Data = std::pair<myClass*, int>;

void myFunction() {            
    // ...

    Data data[5];            
    for (int i = 0; i < 5; ++i) {
        data[i] = {this, i};
        pthread_create(&processIDs[i], NULL, &printIntegerHelper, &data[i]);
    }

    // ... (all created threads are joined here, so
    //      accessing data inside a thread is safe)
}

static void* printIntegerHelper(void* arg) {
    const auto data = *reinterpret_cast<Data*>(arg);
    data.first->printInteger(data.second);
    return nullptr;
}
还要注意,即使以后不使用该值,非void函数也应该对return进行编码。唯一的异常(exception)是int main(...)

关于c++ - 线程可以调用Class Function并访问类数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64658426/

相关文章:

Java并发: some assistance

c - 如何使用 pthread 实现单写入器、多读取器队列?

c++ - 将值从一个函数传递给另一个 C++

c++ - 从 OpenCV FeatureDetector 检索特征类型

c# - 使用 C# 创建线程并为其分配函数

c++ - std::memory_order_acq_rel 对其他线程读取的非原子变量的影响

c - 在 C 中实现定时事件

c++ - Win32/pthreads 线程函数上的 volatile 正确性

c++ - ImageMagick 错误 : Unable to open image

c++ - 如何在主函数中访问订阅者类的公共(public)变量?