|
thrust(unary与binary)中放复杂类到GPU加速
- #include <thrust/device_vector.h>
- #include <iostream>
- #include <string.h>
- using namespace std;
- //thrust(unary与binary)中放复杂类到GPU加速
- struct Teacher
- {
- //string name; // string类型不支持cuda吗? string本身就是stl
- char name[64]; //基础数据类型
- int age;
-
- __host__ __device__
- Teacher() {
- // : name("xxx"),age(10)
- age = 10;
- strcpy(name, "XXX");
- //error: identifier "std::cout" is undefined in device code
- //cout << "无参构造" << endl;
- }
-
- __host__ __device__
- Teacher(const char *pname, int _age) {
- //warning: conversion from a string literal to "char *" is deprecated
- //在所有声明char *的地方都要加上const
- age = _age;
- strcpy(name, pname); //这个支持gpu操作?
- }
- __host__
- void print_teacher_info(){
- //warning: address of a host variable "std::cout"
- std::cout << "name=" << name << ",age=" << age << std::endl;
- }
- };
- struct get_age_unary_op
- : public thrust::unary_function< Teacher, int >
- {
- // unary_op; //用于transform 一元操作
-
- __host__ __device__
- int operator()(const Teacher& t) const
- {
- //函数对象:()操作符的重载
- return t.age;
- }
- };
- struct jjj_plus : public thrust::binary_function<int,int,int>
- {
- //自定义二元函数对象 这是基础数据类型的
- __host__ __device__
- int operator()(int a, int b)
- {
- return a+b;
- }
- };
- int main(){
- int a[6] = {1,2,3,4,5,6};
- thrust::device_vector<int> d1(a,a+6);
- thrust::copy(d1.begin(),d1.end(), std::ostream_iterator<int>(std::cout, "\n"));
- int sum1 = thrust::reduce(d1.begin(),d1.end());
- int sum2 = thrust::reduce(d1.begin(),d1.end(),0,thrust::plus<int>());
- int sum3 = thrust::reduce(d1.begin(),d1.end(),0,jjj_plus());
- std::cout << "求和1=" << sum1 << std::endl;
- std::cout << "求和2=" << sum2 << std::endl;
- std::cout << "求和3=" << sum3 << std::endl;
- //求老师的年龄之和呢?
- Teacher t1("zhang_san", 30), t2("li_si", 33), t3;
- t1.print_teacher_info();
- t2.print_teacher_info();
- t3.print_teacher_info();
- //Teacher t_array[3] = {t1,t2,t3};
- //thrust::device_vector<Teacher> d2(t_array,t_array+3);
- thrust::device_vector<Teacher> teacher_array;
- //thrust::system::system_error'
- //what(): for_each: failed to synchronize: cudaErrorLaunchFailure: unspecified launch failure
- teacher_array.push_back(t1);
- teacher_array.push_back(t2);
- teacher_array.push_back(t3);
- // 1元操作用来 转换 容器里的每个元素 2元操作用来操作相邻的value
- int result_sum = thrust::transform_reduce(teacher_array.begin(), teacher_array.end(), get_age_unary_op(), 0, jjj_plus());
- std::cout << "result_sum=" << result_sum << std::endl;
-
- return 0;
- }
- /**
- for_each: failed to synchronize: cudaErrorLaunchFailure: unspecified launch failure
- 已放弃 (核心已转储)
- 具体代码:
- thrust::device_vector<Teacher> teacher_array(3);
- Teacher里有成员变量:
- string name; // string类型不支持cuda吗?
- 分析:string是c++的stl
- 改用 char name[64];
- string name = "jiangjinju";
- //字符串怎么放到gpu上去?
- thrust::device_vector<string> d1(1); //会报错
- */
复制代码
|
|