c++ - 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 个元素相除
解决方案
在这里,您定义了 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
字段以确定是加、减、乘还是除。
推荐阅读
- android-studio - Flutter, set android SDK path in ubuntu
- android - Could not find com.github.MasayukiSuda:Mp4Composer-android:v0.3.9
- javascript - Why are clones moving but not original?
- c++ - Eigen RowVector 超出范围会产生“运行时检查失败 #2 - 变量 X 周围的堆栈已损坏”
- symfony4 - Sulu 中的其他页面类型
- ios - swift: MongoDB 领域没有同步到移动设备
- css - 如何将 flexbox 元素移动到另一行?
- java - java.lang.IllegalMonitorStateException (java selenium)
- c# - C# ASP.NET Core 2.1/Entity Framework:实体集合不保存
- php - PHP Laravel,如何检查字符串日期和时间是否不在过去