首页 > 解决方案 > c++中线程是如何实现的

问题描述

#include <pthread.h>
#include <iostream>
#include <iomanip>

#define NOPER 4

struct operation
{
    int val1;
    int val2;
    int op;
    double result;
};

void *calculator(void *pos_void_ptr)
{
    struct operation *pos_ptr = (struct operation *)pos_void_ptr;
    switch(pos_ptr->op)
    {
        case 0: pos_ptr->result = pos_ptr->val1 + pos_ptr->val2; 
                break;
        case 1: pos_ptr->result = pos_ptr->val1 - pos_ptr->val2; 
                break;
        case 2: pos_ptr->result = pos_ptr->val1 * pos_ptr->val2; 
                break;
        case 3: if (pos_ptr->val2 != 0)
                    pos_ptr->result = (double) pos_ptr->val1 / pos_ptr->val2; 
                else
                    pos_ptr->result = 0;         
                break;
    }
    return NULL;
}

int main()
{
    static struct operation operations[NOPER];
    pthread_t tid[NOPER];

    for(int i=0;i<NOPER;i++)
    {
        operations[i].op = i;
        std::cin >> operations[i].val1;
        std::cin >> operations[i].val2;
        if(pthread_create(&tid[i], NULL, calculator, &operations[i])) 
        {
            fprintf(stderr, "Error creating thread\n");
            return 1;

        }       
    }
    // Wait for the other threads to finish.
    for (int i = 0; i < NOPER; i++)
            pthread_join(tid[i], NULL);
    for (int i = 0; i < NOPER; i++)
    {
        switch(operations[i].op)
        {
            case 0: std::cout << operations[i].val1 << " + " << operations[i].val2 << " = " << std::fixed << std::setprecision(2) << operations[i].result << std::endl;
                    break;
            case 1: std::cout << operations[i].val1 << " - " << operations[i].val2 << " = " << std::fixed << std::setprecision(2) << operations[i].result << std::endl;
                    break;
            case 2: std::cout << operations[i].val1 << " * " << operations[i].val2 << " = " << std::fixed << std::setprecision(2) << operations[i].result << std::endl;
                    break;
            case 3: std::cout << operations[i].val1 << " / " << operations[i].val2 << " = " << std::fixed << std::setprecision(2) << operations[i].result << std::endl;
                    break;
        }
    }
    return 0;
}

我试图对里面的内容有一个基本的了解

void *calculator(void *pos_void_ptr)
    {
        struct operation *pos_ptr = (struct operation *)pos_void_ptr;
        switch(pos_ptr->op)

以及这些参数是什么

(pthread_create(&tid[i], NULL, calculator, &operations[i])

以及如何在任何程序中实现这一点?该程序需要 2 个输入 4 次,然后将前 2 个元素相加,然后将第二个 2 个元素相乘,然后减去第三个 2 个元素,然后将第四个 2 个元素相除

标签: c++pthreads

解决方案


在这里,您定义了 4 个稍后将传递给的线程标识符pthread_create

pthread_t tid[NOPER];

然后创建 4 个线程:

pthread_create(&tid[i], NULL, calculator, &operations[i])

第一个参数是pthread_t标识符,第二个是pthread_attr_t可以用pthread_attr_init函数初始化的类型的可选属性参数,第三个是新线程将执行的函数的名称,第四个是传递的函数的参数作为第三个论点。

calculator函数中,您基本上将 void 指针参数转换为operation结构并打开其op字段以确定是加、减、乘还是除。


推荐阅读