Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple thread code fail?

I'm trying to make it do that I can't call threads from a loop. But when I run it I get a runtime error:

terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument Thread #1

#include <iostream>
#include <vector>
#include <memory>
#include <thread>
#include <mutex>

std::mutex m;
static int thread_count;

auto foo = [&] {
    std::lock_guard<std::mutex> lock(m);
    std::cout << "Thread #" << ++thread_count << std::endl;
};

int main()
{
    std::vector<std::shared_ptr<std::thread>>
             threads(20, std::make_shared<std::thread>(foo));

    for (const auto& th : threads)
        th->join();
}
like image 362
template boy Avatar asked Jun 11 '14 17:06

template boy


People also ask

What is a thread error?

The "SYSTEM THREAD EXCEPTION NOT HANDLED" is a common Windows 10 error that occurs mainly due to an outdated or incompatible driver. What makes it trickier to fix than other BSODs is that multiple drivers can cause the issue and sometimes your computer may not detect them all.

What happens if a thread is not joined?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything. But this some point is non-deterministic.

Why is multithreading so hard?

Multi-threaded programming is probably the most difficult solution to concurrency. It basically is quite a low level abstraction of what the machine actually does. There's a number of approaches, such as the actor model or (software) transactional memory, that are much easier.

What is a coding thread?

With computer programming, a thread is a small set of instructions designed to be scheduled and executed by the CPU independently of the parent process. For example, a program may have an open thread waiting for a specific event to occur or running a separate job, allowing the main program to perform other tasks.


1 Answers

Your code only actually creates one child thread, and therefore it calls join() on that one thread 20 times.

To verify this, you could add the following loop right after you construct the vector:

for (int i=1; i<threads.size(); ++i)
    assert(threads[i - 1].get() == threads[i].get());

You likely want to create your vector with some form of:

std::vector<std::shared_ptr<std::thread>> threads(20);
for (auto & thread : threads)
    thread = std::make_shared<std::thread>(foo);
like image 116
Bill Lynch Avatar answered Sep 29 '22 23:09

Bill Lynch