总结了下,通过状态来实现线程工作切换的1对N多线程模型(1个调度,多个工作的模型),一般的代码结构大致如下,与大家分享下,希望听到更好的建议和想法。
首先是状态数据结构
- enum thread_status
- {
- status_free = 1,
- status_ready = 2,
- status_running = 3,
- status_over = 4,
- status_dead = 5
- };
其次是线程体结构(这个结构作为pthread_create时的参数)
- typedef struct
- {
- pthread_t thread; //thread
- unsigned char status; //status
- unsigned int index;
- }thread_t;
最后是线程体(thread_func的一般代码结构)
初始化:
- for ( index = 0; index < pp->thread_num; index++)
- {
- pp->thread_list[index].status = status_free;
- pp->thread_list[index].index = index;
- //create thread
- if (pthread_create (
- &(pp->thread_list[index].thread), //thread entry
- 0, //attribute
- app_thread, //start function
- pp->thread_list + index))//parameter passed to thread function
- {
- printf ("create thread for thread %u failed\n", index);
- return -1;
- }
- }
运行时:
- void * app_thread(void*data)
- {
- thread_t * pt = (thread_t*)data;
- pthread_detach (pthread_self());
- while (pt->status != status_dead)
- {
- //when it is free, do nothing...
- if (pt->status == status_free)
- {
- printf ("thread %u is free now\n", pt->index);
- sleep (1);
- continue;
- }
-
- //ready means it ought to do something,free -> ready is changed by outter thread
- //but not itself
- if (pt->status == status_ready)
- {
- printf ("thread_%d: ready....go !!!\n");
- pt->status = status_running;
- continue;
- }
- //running, do something
- if (pt->status == status_running)
- {
- while (do_some_thing())
- {
- sleep (1);
- }
- //when everything is done, change status to status_over myself
- pt->status = status_over;
- continue;
- }
- //when i am running over, just waitting someone else to change the
- //status to status_ready to run new tasks or status_dead to exit
- if (pt->status == status_over)
- {
- sleep(1);
- }
- //it's time to say goodbye...
- if (pt->status == status_dead)
- {
- printf ("good luck, i'm now exiting..bye\n");
- break;
- }
- }
- pthread_exit (0);
- }
阅读(5096) | 评论(2) | 转发(0) |