线程如何在 C++ 中实现

how thread is implemented in c++

本文关键字:实现 C++ 线程      更新时间:2023-10-16
#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 threadn");
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 个元素

在这里,您定义了 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字段以确定是加、减、乘还是除