6.8 扩展线程接口类(2)
在程序清单6-3中,第3行~第10行定义的构造函数为SchedAttr这个类初始化一个线程属性对象。它将inheritsched属性设置为PTHREAD_EXPLICIT_SCHED,这样使用这个属性的对象创建的线程负责定义它的调度策略和优先级,而不是从创建者线程继承调度策略和优先级。默认情况下,线程的状态是JOINABLE。其他方法的含义一看便知:
- setPriority(int Priority)
- setSchedPolicy(int Policy)
- setContentionscope(int Scope)
- setDetached()
- setJoinable()
在第20行调用pthread_join( )之前,使用join( )检查线程是不是可结合的。当在第78行中创建线程时,pthread_create( )使用SchedAttr对象:
- pthread_create(&Tid, &SchedAttr, thread,this);
程序清单6-4显示了filter_thread的定义。
程序清单6-4
- //Listing 6-4 A definition of the filter_thread class.
-
- 1 #include "thread_object.h"
- 2
- 3
- 4 filter_thread::filter_thread(void)
- 5 {
- 6 pthread_attr_init(&SchedAttr);
- 7
- 8
- 9 }
- 10
- 11
- 12 filter_thread::~filter_thread(void)
- 13 {
- 14
- 15 }
- 16
- 17 void filter_thread::do_something(void)
- 18 {
- 19 struct sched_param Param;
- 20 int Policy;
- 21 pthread_t thread_id = pthread_self();
- 22 string Schedule;
- 23 string State;
- 24 string Scope;
- 25
- 26 pthread_getschedparam(thread_id,&Policy,&Param);
- 27 if(NewPolicy == SCHED_RR){Schedule.assign("RR");}
- 28 if(NewPolicy == SCHED_FIFO){Schedule.assign("FIFO");}
- 29 if(NewPolicy == SCHED_OTHER){Schedule.assign("OTHER");}
- 30 if(NewState == PTHREAD_CREATE_DETACHED){State.assign("DETACHED");}
- 31 if(NewState == PTHREAD_CREATE_JOINABLE){State.assign("JOINABLE");}
- 32 if(NewScope == PTHREAD_SCOPE_PROCESS){Scope.assign("PROCESS");}
- 33 if(NewScope == PTHREAD_SCOPE_SYSTEM){Scope.assign("SYSTEM");}
- 34 cout << Name << ":" << thread_id << endl
- 35 << "----------------------" << endl
- 36 << " priority: "<< Param.sched_priority << endl
- 37 << " policy: "<< Schedule
<< endl - 38 << " state: "<< State << endl
- 39 << " scope: "<< Scope
<< endl << endl; - 40
- 41 }
- 42
在程序清单6-4中,第4行~第9行的filter_thread构造函数使用线程属性对象SchedAttr进行初始化。定义了do_something( )方法。在filter_thread中,这个方法将如下线程信息发送到cout:
线程名称
线程id
优先级
调度策略
状态
范围
有些值可能未被初始化,因为它们不是在属性对象中设置的。下一章将会对这个方法进行重新定义。
现在可以创建多个filter_thread对象,每个对象可以设置线程的属性。程序清单6-5显示了如何创建多个filter_thread对象。
程序清单6-5
- //Listing 6-5 is main line to create multiple filter_thread objects.
-
- 1 #include "thread_object.h"
- 2 #include <unistd.h>
- 3
- 4
- 5 int main(int argc,char *argv[])
- 6 {
- 7 filter_thread MyThread[4];
- 8
- 9 MyThread[0].name("Proteus");
- 10 MyThread[0].setSchedPolicy(2);
- 11 MyThread[0].setPriority(7);
- 12 MyThread[0].setDetached();
- 13
- 14 MyThread[1].name("Stand Alone Complex");
- 15 MyThread[1].setContentionScope(1);
- 16 MyThread[1].setPriority(5);
- 17 MyThread[1].setSchedPolicy(2);
- 18
- 19 MyThread[2].name("Krell Space");
- 20 MyThread[2].setPriority(3);
- 21
- 22 MyThread[3].name("Cylon Space");
- 23 MyThread[3].setPriority(2);
- 24 MyThread[3].setSchedPolicy(2);
- 25
- 26 for(int N = 0;N < 4;N++)
- 27 {
- 28 MyThread[N].run();
- 29 MyThread[N].join();
- 30 }
- 31 return (0);
- 32 }