pthread_detach pthread_create实例

//pool.h
1
#ifndef POOL_H 2 #define POOL_H 3 #include <pthread.h> 4 5 class pool 6 { 7 public: 8 pool(); 9 ~pool(); 10 11 void func(); 12 static void *schedule(void *ptr); 13 int schedule_thread(); 14 /* 15 private: 16 pthread_t pid; 17 void *params; 18 */ 19 }; 20 21 #endif // POOL_H

//pool.cpp
1
#include <iostream> 2 #include <stdio.h> 3 #include <pthread.h> 4 #include "pool.h" 5 using namespace std; 6 pool::pool() 7 { 8 cout << "pool()" << endl; 9 } 10 11 pool::~pool() 12 { 13 cout << "~pool()" << endl; 14 } 15 16 void pool::func(){ 17 cout << "pool::func" << endl; 18 } 19 20 //void *pool::schedule(void *ptr){ 21 void *pool::schedule(void *ptr){ 22 cout << "enter pool::schedule" << endl; 23 //unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己, 24 int res = pthread_detach(pthread_self()); 25 if(res != 0){ 26 printf("please check /proc/%ld/maps\n", pthread_self()); 27 } 28 pool *p = (pool *)ptr; 29 p->func(); 30 cout << "leave schedule" << endl; 31 return 0; 32 } 33 34 int pool::schedule_thread(){ 35 cout << "enter pool::schedule_thread" << endl; 36 pthread_t pid; 37 //if(pthread_create(&pid , NULL ,schedule, (void *)this) != 0){ 38 if(pthread_create(&pid , NULL ,schedule, (void *)this) != 0){ 39 cerr << "schedule thread create fail" << endl; 40 return -1; 41 } 42 cout << "leave pool::schedule_thread" << endl; 43 return 0; 44 }
//main.cpp
#include<stdio.h> #include <stdlib.h> #include <string.h> #include "pool.h" int main(void) { pool *pl = new pool(); // pl.func(); pool::schedule(pl); //pl.schedule_thread(); delete pl; return 0; }

 

 

posted @ 2016-07-08 18:02  PKICA  阅读(712)  评论(0编辑  收藏  举报