title: Using thrust with printf / cout
body: <p>I'm trying to learn how to use CUDA with thrust and I have seen some piece of code where the printf function seems to be used from the device.</p>
  
  <p>Consider this code:</p>
  
  <pre><code>#include &lt;thrust/host_vector.h&gt;
  #include &lt;thrust/device_vector.h&gt;
  #include &lt;cstdio&gt;
  
  struct functor
  {
    __host__ __device__
    void operator()(int val)
    {
        printf("Call for value : %d\n", val);
    }
  };
  
  int main()
  {
      thrust::host_vector&lt;int&gt; cpu_vec(100);
      for(int i = 0 ; i &lt; 100 ; ++i)
        cpu_vec[i] = i;
      thrust::device_vector&lt;int&gt; cuda_vec = cpu_vec; //transfer to GPU
      thrust::for_each(cuda_vec.begin(),cuda_vec.end(),functor());
  }
  </code></pre>
  
  <p>this seems to run fine and prints 100 times the message "Call for value : " followed by a number.</p>
  
  <p>now if I include iostream and replace the printf line with a C++ stream-based equivalent</p>
  
  <pre><code>std::cout &lt;&lt; "Call for value : " &lt;&lt; val &lt;&lt; std::endl;
  </code></pre>
  
  <p>I get compilation warnings from nvcc and the compiled program will not print anything.</p>
  
  <pre><code>warning: address of a host variable "std::cout" cannot be directly taken in a device function
  warning: calling a __host__ function from a __host__ __device__ function is not allowed
  warning: calling a __host__ function("std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator &lt;&lt;") from a __host__ __device__ function("functor::operator ()") is not allowed
  </code></pre>
  
  <ol>
  <li>Why does it work with printf?</li>
  <li>Why does it <em>not</em> work with cout?</li>
  <li>What is actually run on GPU? I'd guess, at least sending to stdout requires some CPU work.</li>
  </ol>