Skip to content

Instantly share code, notes, and snippets.

@bramton
Last active January 24, 2024 15:08
Show Gist options
  • Save bramton/94954f78b000e28938e597e01cb3b8f4 to your computer and use it in GitHub Desktop.
Save bramton/94954f78b000e28938e597e01cb3b8f4 to your computer and use it in GitHub Desktop.
C++ threads with lambda expression
#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