什么叫事务线程
举个例子:
我们写一个IM客户端的登录子线程,则该子线程会有这么几个事务要处理
No.1 TCP Socket物理连接
No.2 逻辑登录
No.3 好友在线查询
No.4 状态更新
我们通常的代码写法是
- void ThreadLogin()
- {
- try
- {
- if(fail(物理连接))
- throw;
- if(fail(登录))
- throw;
- if(fail(查询好友))
- throw;
- if(fail(更新))
- throw;
- }
- catch(exception)
- {
- }
- }
串行的逻辑用串行的代码写,不太好看,况且中途如果主线程发出取消指令,还不好处理。
这里扩展的thread类,就是来解决这个问题的,他会提供给程序员一种事件处理的模式
- class threadLogin
- {
- void onEventConnect()
- {
- 物理连接
- }
- void onEventLogin()
- {
- 登录
- }
- void onEventQuery()
- {
- 查询
- }
- void onEventUpdate()
- {
- 更新
- }
- }
源码如下
虚拟函数thread::on_process()处理各种事务事件
虚拟函数thread::on_process_end()是所有事务处理完毕事件
虚拟函数thread::on_process_fail()是事务处理出现错误,这时所有事务被取消,线程终止
这里给一个简单的范例,
总共线程要完成3件事务,其中第二个事务要求用户确认是否继续
- #define PROCESS_1 1
- #define PROCESS_2 2
- #define PROCESS_3 3
- class thdex: public thread
- {
- public:
- virtual void on_process()
- {
- thread::on_process();
- if(this->level==PROCESS_1)
- {
- cout << "work on process 1..." << endl;
- Sleep(100);
- cout << "process 1 done." << endl;
- this->next();
- }
- else if(this->level==PROCESS_2)
- {
- cout << "work on process 2..." << endl;
- this->timeout = -1;
- if(IDNO==::MessageBox(0,"are your want continue?","ask",MB_ICONQUESTION|MB_YESNO))
- {
- this->lasterror = "canceled by user";
- this->fail();
- }
- else
- {
- Sleep(100);
- cout << "process 2 done." << endl;
- this->next();
- }
- }
- else if(this->level==PROCESS_3)
- {
- cout << "work on process 3..." << endl;
- Sleep(100);
- cout << "process 3 done." << endl;
- this->next();
- }
- }
- virtual void on_process_fail()
- {
- cout << this->lasterror << endl;
- }
- virtual void on_process_end()
- {
- cout << "all process done." << endl;
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- thdex t;
- t.safestart();
- t.startprocess(PROCESS_1,PROCESS_3);
- char buf[10];
- gets_s(buf,sizeof buf);
- t.safestop();
- return 0;
- }
阅读(903) | 评论(0) | 转发(0) |