线程如何在 C++ 中实现
how thread is implemented in 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 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
字段以确定是加、减、乘还是除
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的