Why Does This Simple Std::Thread Example Not Work

Why does this simple std::thread example not work?

You have to join std::threads, just like you have to join pthreads.

int main( int argc, char *argv[] )
{
std::thread t( doSomeWork );
t.join();
return 0;
}

UPDATE: This Debian bug report pointed me to the solution: add -pthread to your commandline. This is most probably a workaround until the std::thread code stabilizes and g++ pulls that library in when it should (or always, for C++).

C++11 Thread not working

When I use C++11 threads with GCC, i use:

g++ -std=c++0x -pthread -g main.cpp

That works for me.

Simple example of threading in C++

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

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 first argument is 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.

Error nested std::thread inside a thread throws an error

You are reading and writing to sum and thread_group from multiple threads at the same time. A simple solution is you make sure that only one thread at a time has access to them by using a std::mutex and locking it while accessing those variables. You also need to make sure that all threads are finished working with thread_group before it gets destroyed. I added a counter and a std::condition_variable to take care of that.

Example (using C++20 std::jthreads instead to not have to call the non-existing join_all function):

#include <condition_variable>
#include <iostream>
#include <list> // using list instead of vector to avoid realloc
#include <mutex>
#include <thread>
#include <vector>

using container = std::list<std::jthread>;

void simple() { std::cout << "Nested Thread\n"; }

void function(int& counter, std::mutex& mtx,
std::condition_variable& cv, container& thread_group)
{
std::lock_guard lock(mtx);
thread_group.emplace_back(simple);
++counter; // so that main thread can check that all is done
cv.notify_one(); // signal main that the work is done
}

int main(){
// Container for storing threads
container thread_group;
std::mutex mtx;
std::condition_variable cv;

int starting_threads = 10;
int counter = 0;
for (int n = 1; n <= starting_threads; n++) {
std::lock_guard lock(mtx); // lock while adding thread
// Add thread to the container
thread_group.emplace_back(function, std::ref(counter), std::ref(mtx),
std::ref(cv), std::ref(thread_group));
}

std::unique_lock lock(mtx);
// wait until all threads are done with thread_group
// before letting thread_group go out of scope and get
// destroyed
while(counter < starting_threads) cv.wait(lock);

std::cout << thread_group.size() << '\n';

// wait for all threads to finish (jthread's auto-join)
}

Possible output:

Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
Nested Thread
20
Nested Thread

C++ threading classes not working and giving functional and thread file errors

Member functions are not part of objects but class. You need full qualified function name. You need to do following:

thread t(&Greeting::hi, &g, str);

Also, you accidentally used 't' as name of staring variable and for the thread, which i modified to str for string.

std::thread does not start immediately as expected (c++11)

You are not measuring what you think you are measuring here:

start= std::chrono::system_clock::now();
auto Thread = std::thread([](){std::cout<<"Excuting thread"<<std::endl;});
stop = std::chrono::system_clock::now();

The stop timestamp only gives you an upper bound on how long it takes main to spawn that thread and it actually tells you nothing about when that thread will start doing any actual work (for that you would need to take a timestamp inside the thread).

Also, system_clock is not the best clock for such measurements on most platforms, you should use steady_clock by default and resort to high_resolution_clock if that one doesn't give you enough precision (but note that you will have to deal with the non-monotonic nature of that clock by yourself then, which can easily mess up the gained precision for you).

As was mentioned already in the comments, spawning a new thread (and thus also constructing a new std::thread) is a very complex and time-consuming operation. If you need high responsiveness, what you want to do is spawn a couple of threads during startup of your program and then have them wait on a std::condition_variable that will get signalled as soon as work for them becomes available. That way you can be sure that on an otherwise idle system a thread will start processing the work that was assigned to him very quickly (immediately is not possible on most systems due to how the operating system schedules threads, but the delay should be well under a millisecond).

C++ Visual Studio 13 using threads: minimal example not working

The above code works in VS 2013 (but also in VS 2012, VS 2015).

Try to create a new project and copy the code there. VS behaves strange sometimes. Also removing the .sdf file may help together with "build -> clean solution".



Related Topics



Leave a reply



Submit