- 论坛徽章:
- 1
|
尔等根本体会不到写C++的乐趣
- #include <my_pthread.h>
- #include <stdio.h>
- struct foo
- {
- int n;
- void *test(void *arg)
- {
- for(int i = 0; i < 10; ++i)
- printf("%d \n", ++n);
- return NULL;
- }
- };
- int main()
- {
- foo f;
- pthread_t id;
- my_pthread_create(&f, &id, NULL, &foo::test, NULL);
- pthread_join(id, NULL);
- return 0;
- }
复制代码 以下为 my_pthread.h
- #ifndef INC_THREAD_PROXY_H_
- #define INC_THREAD_PROXY_H_
- #include <pthread.h>
- #include <semaphore.h>
- template <class T>
- class thread_proxy_imp
- {
- protected:
- typedef struct
- {
- void *(T::*start_routine_)(void *);
- void *arg_;
- T *obj_;
- sem_t sem_;
- } thread_param;
- static void *thread_proxy_entry(void *arg)
- {
- thread_param *param_ptr = reinterpret_cast<thread_param *>(arg);
- thread_param param = *param_ptr;
- sem_post(¶m.sem_);
- return (param.obj_->*param.start_routine_)(param.arg_);
- }
- public:
- int create(
- T *obj,
- pthread_t *thread,
- const pthread_attr_t *attr,
- void *(T::*start_routine) (void *),
- void *arg)
- {
- int rt;
- thread_param param = {start_routine, arg, obj};
-
- sem_init(¶m.sem_, 0, 0);
- rt = pthread_create(thread,
- attr,
- thread_proxy_imp::thread_proxy_entry,
- reinterpret_cast<void *>(¶m));
- if(rt == 0) sem_wait(¶m.sem_);
- sem_destroy(¶m.sem_);
- return rt;
- }
- };
- template<class T>
- int my_pthread_create(
- T *obj,
- pthread_t *thread,
- const pthread_attr_t *attr,
- void *(T::*start_routine) (void *),
- void *arg)
- {
- return thread_proxy_imp<T>().create(obj, thread, attr, start_routine, arg);
- }
- #endif
复制代码 |
|