Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Simple example of threading in C++

Would someone be able to post a basic illustration of beginning two (Object Oriented) strings in C++?

I'm searching for actual C++ string objects that I can broaden run techniques on (or something almost identical) instead of calling a C-style string library.

I left out any OS-specific requests in the expectations that whoever answered would answer with cross-platform libraries to utilize. I'm simply making that explicit now.
by

3 Answers

rahul07
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).
pankajshivnani123
#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
cout << id << "\n";
}

/*
* Spawns n threads
/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}

for (auto& th : threads) {
th.join();
}
}

int main()
{
spawnThreads(10);
}
sandhya6gczb
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:

Class.h

class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};

Class.cpp

#include "DataManager.h"

void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}

bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}

Note that this example doesn't get into mutex or locking.

Login / Signup to Answer the Question.