User Tools

Site Tools


c:c_threads:create_a_thread:create_a_thread_with_a_function_pointer

This is an old revision of the document!


C - C++ Threads - Create a thread - Create a thread with a function pointer

Just pass in the address of a function to the thread constructor.

The thread will start executing the function immediately.

#include <iostream>
#include <thread>
 
void ShowMessage()
{
  std::cout << "Firing sidewinder missile " << std::endl;
}
 
int main()
{
  // Create a thread with a function pointer.
  std::thread t1(ShowMessage);
  t1.join();
 
  return 0;
}

With Arguments

#include <iostream>
#include <string>
#include <thread>
 
 
void ShowMessage(std::string name, int age)
{
  std::cout << "Hello " << name << ".  You are " << age << " years old." << std::endl;
}
 
int main()
{
  thread t1(ShowMessage, "Peter", 21);
  t1.join();
  return 0;
}
c/c_threads/create_a_thread/create_a_thread_with_a_function_pointer.1614937252.txt.gz · Last modified: 2021/03/05 09:40 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki