Last active
January 24, 2024 15:08
-
-
Save bramton/94954f78b000e28938e597e01cb3b8f4 to your computer and use it in GitHub Desktop.
C++ threads with lambda expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <thread> | |
#include <vector> | |
#include <unistd.h> // For sleep() | |
using namespace std; | |
void blaat(unsigned int t) { | |
cout << "Received param: " << t << endl; | |
} | |
int main() { | |
unsigned int m_threads = 10; | |
unsigned int points[m_threads]; | |
for (unsigned int t = 0; t < m_threads; t++) { | |
points[t] = t; | |
} | |
std::vector<std::thread> threadList(m_threads); | |
for (unsigned int t = 0; t < m_threads; t++) { | |
threadList[t] = std::thread( | |
[&points](const unsigned int x) { | |
blaat(x); | |
points[x] *= 2; | |
sleep(1); | |
}, | |
t); | |
} | |
for (auto& t : threadList) | |
t.join(); | |
for (unsigned int t = 0; t < m_threads; t++) { | |
cout << "Point value: " << points[t] << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment