Skip to content

Instantly share code, notes, and snippets.

@Gerjo
Created October 25, 2012 16:10
Show Gist options
  • Save Gerjo/3953719 to your computer and use it in GitHub Desktop.
Save Gerjo/3953719 to your computer and use it in GitHub Desktop.
Shared pointer and threading
#include <cstdlib>
#include <map>
#include <string>
#include <memory>
#include <thread>
#include <iostream>
#include <functional>
#include <unistd.h>
using std::shared_ptr;
using std::cout;
using std::endl;
using std::thread;
class Example {
public:
Example() {
cout << "New Example constructed" << endl;
}
~Example() {
cout << "Example has been deleted." << endl;
}
};
void callback(shared_ptr<Example> str) {
cout << "Starting thread." << endl;
sleep(1);
cout << "Ending thread." << endl;
}
int main(int argc, char** argv) {
thread* t1;
thread* t2;
thread* t3;
Example* example = new Example();
{
shared_ptr<Example> shared(example);
t1 = new thread(callback, shared);
t2 = new thread(callback, shared);
t3 = new thread(callback, shared);
cout << "Shared runs out of scope." << endl;
}
t3->join();
t2->join();
t1->join();
delete t3;
delete t2;
delete t1;
// It would appear that by this point, the "example" pointer is deleted, too!
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment