Question about threads

So everytime you run a C++ program by default you have 1 thread the main thread which is the whole program, then you can instantiate multiple threads to perform multiple tasks at the same time correct?
Last edited on
That is correct. However, multithreaded programming in C++ is actually quite a complex topic because of race conditions with shared data.

I don't recommend it for beginners. Often times, beginners think they need a 2nd thread to do something, when really it could (and should) all be done in one thread.



EDIT:

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//global string object:
string example = "";

// a function running in one thread
void thread_a()
{
    example = "foo";
}

// a function running in a second thread
void thread_b()
{
    example = "bar";
    cout << example;
}


Assume that both threads are running at more or less the same time. What do you expect line 14 to output?

a: foo
b: bar
c: random garbage
d: program crash
e: memory leak



The answer is: any of the above. If 'example' is getting poked and prodded by multiple threads at the same time, things get very bad and pretty much anything can happen. This is especially bad with std::string because it's a complex class that manages memory, so it might lead to memory corruption, leaks, crashes, etc.

So yeah -- complex topic. Before you dive in and start adding threads... ask yourself if you really need to.
Last edited on
I second what Disch said. I had a program that was taking too long to complete, so I thought I'd try speeding it up with threads. It helped a little, until I noticed that some of my variables were being corrupted. I ended up removing the multi-threading and rewriting one of my functions instead. Rewriting the function provided a much greater speed boost than multi-threading.
Topic archived. No new replies allowed.