Skip to content

Instantly share code, notes, and snippets.

@giantchen
Created November 22, 2011 01:53
Show Gist options
  • Save giantchen/1384659 to your computer and use it in GitHub Desktop.
Save giantchen/1384659 to your computer and use it in GitHub Desktop.
Thread detach
#pragma once
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <pthread.h>
class Thread : boost::noncopyable
{
public:
typedef boost::function<void ()> ThreadFunc;
explicit Thread(const ThreadFunc& func)
: pthreadId_(0),
func_(func)
{
}
~Thread() {}
void tie(const boost::shared_ptr<void>& obj)
{
tie_ = obj;
}
void start()
{
pthread_create(&pthreadId_, NULL, &startThread, this);
}
void detach()
{
pthread_detach(pthreadId_);
}
void join()
{
pthread_join(pthreadId_, NULL);
}
private:
static void* startThread(void* me)
{
Thread* thread = static_cast<Thread*>(me);
thread->runInThread();
return NULL;
}
void runInThread()
{
boost::shared_ptr<void> guard = tie_;
tie_.reset();
func_();
}
pthread_t pthreadId_;
ThreadFunc func_;
boost::shared_ptr<void> tie_;
};
#include "Thread.h"
#include <boost/bind.hpp>
#include <stdio.h>
void print(int id)
{
printf("Hello world %d\n", id);
}
int main(int argc, char* argv[])
{
int n = atoi(argv[1]);
for (int i = 0; i < n; ++i)
{
boost::shared_ptr<Thread> thread(new Thread(boost::bind(&print, i)));
thread->tie(thread);
thread->start();
thread->detach();
}
pthread_exit(NULL);
//sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment