Multithreading
Multithreading is the ability of multiple parts of same code to be executed at the same time. It is different from multitasking - while multitasking appears to be parallel execution, it is not executed parallelly in reality. It's just switching between two tasks, but at a very fast speed. In multitasking, individual cores pick up individual threads to work upon.
Multithreading in C++
Here, we are creating three threads to execute 3 functions parallelly. Try compiling the above piece of code. You might get the below error -
To solve, the above issue give -lpthread
flag with the g++ command. The code will be compiled successfully, now run ./a.out
- at this point you might encounter another issue.
To solve this issue, add worker1.join();
and similar lines for the other worker threads just before the final return 0 statement. That is after line 25, and before line 26. Now, if you execute the +, - will come in a haphazard way (the output might not exact be the same for you)
This join() function basically tells the current/main thread to wait until the worker thread is done with its task, and then continue on the main thread tasks.
Multithreading Code to get weather forecast every 2 seconds
Another example of multithreading - Below code snippet keeps printing Working
every 1 second until the user presses 'Enter'.
References:
CodeBeauty Channel - https://www.youtube.com/watch?v=xPqnoB2hjjA
Last updated