Skip to content
Fix Code Error

Simple example of threading in C++

March 13, 2021 by Code Error
Posted By: Zak

Can someone post a simple example of starting two (Object Oriented) threads in C++.

I’m looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.

I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I’m just making that explicit now.

Solution

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor’s arguments are the function the thread will execute, followed by the function’s parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.
Answered By: Anonymous

Related Articles

  • What are the new features in C++17?
  • no match for ‘operator
  • When I'm testing a web app by JUnit and Mockito I…
  • SQL find sum of entries by date including previous date
  • Getting weird compilation error in defining a…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Callback functions in C++
  • Gradle error: Execution failed for task…
  • I do not use TBB, but I get linker errors related to TBB
  • I'm getting an error "invalid use of incomplete type…
  • Simplest way to create Unix-like continuous pipeline…
  • How would I run an async Task method synchronously?
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • insert tables in dataframe with years from 2000 to…
  • unique_ptr is not deleted after calling reset
  • What is the issue with this QOpenGLWidget?
  • Head pointer not accessible when creating a method…
  • Baffling variadic templates exercise
  • org.gradle.api.tasks.TaskExecutionException:…
  • How to use 2 columns as "key" to get MAX value of…
  • Pandas pivot_table: filter on aggregate function
  • Polymer conflict with moment.js?
  • Jetpack Compose and Hilt Conflict
  • How to parse JSON file with Spring
  • Copy a file in a sane, safe and efficient way
  • ClassNotFoundException thrown
  • C++ Need help sorting a 2D string array
  • Trying to overload operator
  • How do I print out the contents of a vector?
  • How to stop a looping thread in Python?
  • Is it possible to declare two variables of different…
  • c++ how to align output with for loop
  • Execution failed for task…
  • Is it possible to print a variable's type in standard C++?
  • is there a way to use the forwarding of std::less…
  • Overload resolution between va_list and ellipsis…
  • How do I keep only the first map and when the game…
  • Reference - What does this regex mean?
  • How to show title in hover - css / jquery
  • VueJS display dynamic modal component
  • I need to sum values with specific condition
  • How to write a large buffer into a binary file in C++, fast?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to overwrite operator in C++ class with a…
  • How to generate a random number in C++?
  • Error with C++20 ranges and std::views::take
  • C++ template,typename and operator
  • Add calculated column to df2 for every row entry in…
  • TypeError: Cannot read property 'first' of undefined…
  • How to convert wstring into string?
  • What is and how to fix…
  • Why does this core dumped error happen in my class?…
  • InfluxDB - ERR_EMPTY_RESPONSE - Used to come up in…
  • OOP can't get value from a class
  • Multithreading: waiting for a thread to finish so I…
  • CSS Float: Floating an image to the left of the text
  • Output not incrementing correctly - C++
  • C++ printing boolean, what is displayed?
  • How do i calculate total without manually inputting it?
  • C++11 introduced a standardized memory model. What…
  • Error: the entity type requires a primary key
  • SQL / Teradata - How can I get the most recent…
  • Update console text from multiple threads not working
  • How to redirect cin and cout to files?
  • Error: Jump to case label
  • Keycloak/Wildfly How to configure all console logs…
  • Polymer 1.0 Trying to make a splitter which works…
  • How to use html template with vue.js
  • Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap
  • What happens at runtime when we have multiple Java threads?
  • C threads corrupting each other
  • Qt program with OpenGL + GLSL integration crashes…
  • When should one use a spinlock instead of mutex?
  • Base type is not converting to derived type yet can…
  • Webpack: Unable to find module with ID: main --…
  • Cannot std::cout an implicitly converted std::string
  • Pointer to incomplete class type is not allowed
  • I've create 3 additional threads in order to run 3…
  • How I can resolve exception…
  • Run two async tasks in parallel and collect results…
  • Checking cin input stream produces an integer
  • How to select rows based on two columns creating an…
  • How many threads is too many?
  • Restful API service
  • C++ : How can I parallelize an n-ary operation on n ranges?
  • How can I read and parse CSV files in C++?
  • Active tab issue on page load HTML
  • C++ error: expected class member or base class name…
  • What exactly is std::atomic?
  • Obtain most recent value for based on index in a…
  • What is the use of join() in Python threading?
  • Moving average in MYSQL without dates but grouped by…
  • How to auto insert the current user into my db when…
  • Oracle manage historical info and new entries
  • Example of AES using Crypto++
  • How to insert data in only one type of Vector in…
  • Why can I not push_back a unique_ptr into a vector?
  • SameSite warning Chrome 77
  • Python Monthly Change Calculation (Pandas)
  • C++ - Proper way to add obiect to std::vector in…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Pandas – Get first row value of a given column

Next Post:

Using only CSS, show div on hover over

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error