深入浅出win32多线程程序设计之线程控制

 

 

    简介:这是深入浅出win32多线程程序设计之线程控制的详细页面,介绍了和线程,有关

的知识,谢谢大家的观看!
    win32线程控制主要实现线程的创建、终止、挂起和恢复等操作,这些操作都依赖于

win32提供的一组api和具体编译器的c运行时库函数。
  1.线程函数
  在启动一个线程之前,必须为线程编写一个全局的线程函数,这个线程函数接受一个32

位的lpvoid作为参数,返回一个uint,线程函数的结构为:
uint threadfunction(lpvoid pparam)
{
 //线程处理代码
 return0;
}

  在线程处理代码部分通常包括一个死循环,该循环中先等待某事情的发生,再处理相关

的工作:
while(1)
{
 waitforsingleobject(…,…);//或waitformultipleobjects(…)
 //do something
}

  一般来说,c++的类成员函数不能作为线程函数。这是因为在类中定义的成员函数,编

译器会给其加上this指针。请看下列程序:
#include "windows.h"
#include <process.h>
class exampletask
{
public:
  void taskmain(lpvoid param);
  void starttask();
};
void exampletask::taskmain(lpvoid param)
{}
void exampletask::starttask()
{
   _beginthread(taskmain,0,null);
}
int main(int argc, char* argv[])
{
   exampletask realtimetask;
   realtimetask.starttask();
   return 0;
}

  程序编译时出现如下错误:
error c2664: '_beginthread' : cannot convert parameter 1 from 'void (void *)' to

'void (__cdecl *)(void *)' none of the functions with this name in scope match

the target type

  再看下列程序:
#include "windows.h"
#include <process.h>
class exampletask
{
public:
  void taskmain(lpvoid param);
};
void exampletask::taskmain(lpvoid param)
{}
int main(int argc, char* argv[])
{
   exampletask realtimetask;
   _beginthread(exampletask::taskmain,0,null);
   return 0;
}

  程序编译时会出错:
error c2664: '_beginthread' : cannot convert parameter 1 from 'void (void *)' to

'void (__cdecl *)(void *)' none of the functions with this name in scope match

the target type

  如果一定要以类成员函数作为线程函数,通常有如下解决方案:
  (1)将该成员函数声明为static类型,去掉this指针;
  我们将上述二个程序改变为:
#include <windows.h>
#include <process.h>
class exampletask
{
public:
  void static taskmain(lpvoid param);
  void starttask();
};
void exampletask::taskmain(lpvoid param)
{}
void exampletask::starttask()
{
   _beginthread(taskmain,0,null);
}
int main(int argc, char* argv[])
{
   exampletask realtimetask;
   realtimetask.starttask();
   return 0;
}

#include <windows.h>
#include <process.h>
class exampletask
{
public:
  void static taskmain(lpvoid param);
};
void exampletask::taskmain(lpvoid param)
{}
int main(int argc, char* argv[])
{
   _beginthread(exampletask::taskmain,0,null);
   return 0;
}

均编译通过。
  将成员函数声明为静态虽然可以解决作为线程函数的问题,但是它带来了新的问题,那

就是static成员函数只能访问static成员。解决此问题的一种途径是可以在调用类静态成员

函数(线程函数)时将this指针作为参数传入,并在改线程函数中用强制类型转换将this转

换成指向该类的指针,通过该指针访问非静态成员。
  
  (2)不定义类成员函数为线程函数,而将线程函数定义为类的友元函数。这样,线程函数

也可以有类成员函数同等的权限;
  我们将程序修改为:
#include "windows.h"
#include <process.h>
class exampletask
{
public:
  friend void taskmain(lpvoid param);
  void starttask();
};
void taskmain(lpvoid param)
{
   exampletask * ptaskmain = (exampletask *) param;
   //通过ptaskmain指针引用
}
void exampletask::starttask()
{
   _beginthread(taskmain,0,this);
}
int main(int argc, char* argv[])
{
   exampletask realtimetask;
   realtimetask.starttask();
   return 0;
}

  (3)可以对非静态成员函数实现回调,并访问非静态成员,此法涉及到一些高级技巧,

在此不再详述。

  2.创建线程
  进程的主线程由操作系统自动生成,win32提供了createthread api来完成用户线程的

创建,该api的原型为:
handle createthread(
 lpsecurity_attributes lpthreadattributes,//pointer to a security_attributes

structure
 size_t dwstacksize, //initial size of the stack, in bytes.
 lpthread_start_routine lpstartaddress,
 lpvoid lpparameter, //pointer to a variable to be passed to the thread
 dword dwcreationflags, //flags that control the creation of the thread
 lpdword lpthreadid //pointer to a variable that receives the thread identifier
);

  如果使用c/c++语言编写多线程应用程序,一定不能使用操作系统提供的createthread

api,而应该使用c/c++运行时库中的_beginthread(或_beginthreadex),其函数原型为:
uint ptr_t _beginthread(
 void(__cdecl *start_address )(void *), //start address of routine that begins

execution of new thread
 unsigned stack_size, //stack size for new thread or 0.
 void *arglist //argument list to be passed to new thread or null
);
uintptr_t _beginthreadex(
 void *security,//pointer to a security_attributes structure
 unsigned stack_size,
 unsigned (__stdcall *start_address)(void *),
 void *arglist,
 unsigned initflag,//initial state of new thread (0 for running or

create_suspended for suspended);
 unsigned *thrdaddr
);

  _beginthread函数与win32 api 中的createthread函数类似,但有如下差异:
  (1)通过_beginthread函数我们可以利用其参数列表arglist将多个参数传递到线程;
  (2)_beginthread 函数初始化某些 c 运行时库变量,在线程中若需要使用 c 运行时库

  3.终止线程
  线程的终止有如下四种方式:
  (1)线程函数返回;
  (2)线程自身调用exitthread 函数即终止自己,其原型为:
void exitthread(uint fuexitcode); 

  它将参数fuexitcode设置为线程的退出码。
  注意:如果使用c/c++编写代码,我们应该使用c/c++运行时库函数_endthread

(_endthreadex)终止线程,决不能使用exitthread!_endthread 函数对于线程内的条件终

止很有用。例如,专门用于通信处理的线程若无法获取对通信端口的控制,则会退出。
  (3)同一进程或其他进程的线程调用terminatethread函数,其原型为:
bool terminatethread(handle hthread,dword dwexitcode); 

  该函数用来结束由hthread参数指定的线程,并把dwexitcode设成该线程的退出码。当

某个线程不再响应时,我们可以用其他线程调用该函数来终止这个不响应的线程。
  (4)包含线程的进程终止。
  最好使用第1种方式终止线程,第2~4种方式都不宜采用。

  4.挂起与恢复线程
  当我们创建线程的时候,如果给其传入create_suspended标志,则该线程创建后被挂起

,我们应使用resumethread恢复它:
dword resumethread(handle hthread); 

  如果resumethread函数运行成功,它将返回线程的前一个暂停计数,否则返回

0xffffffff。
  对于没有被挂起的线程,程序员可以调用suspendthread函数强行挂起之:
dword suspendthread(handle hthread);

  一个线程可以被挂起多次。线程可以自行暂停运行,但是不能自行恢复运行。如果一个

线程被挂起n次,则该线程也必须被恢复n次才可能得以执行。

  5.设置线程优先级
  当一个线程被首次创建时,它的优先级等同于它所属进程的优先级。在单个进程内可以

通过调用setthreadpriority函数改变线程的相对优先级。一个线程的优先级是相对于其所

属进程的优先级而言的。
bool setthreadpriority(handle hthread, int npriority); 

  其中参数hthread是指向待修改优先级线程的句柄,线程与包含它的进程的优先级关系

如下:
   线程优先级 = 进程类基本优先级 + 线程相对优先级
  进程类的基本优先级包括:
  (1)实时:realtime_priority_class;
  (2)高:high _priority_class;
  (3)高于正常:above_normal_priority_class;
  (4)正常:normal _priority_class;
  (5)低于正常:below_ normal _priority_class;
  (6)空闲:idle_priority_class。

  线程的相对优先级包括:
  (1)空闲:thread_priority_idle;
  (2)最低线程:thread_priority_lowest;
  (3)低于正常线程:thread_priority_below_normal;
  (4)正常线程:thread_priority_ normal (缺省);
  (5)高于正常线程:thread_priority_above_normal;
  (6)最高线程:thread_priority_highest;
  (7)关键时间:thread_priotity_critical。
  下图给出了进程优先级和线程相对优先级的映射关系:
 

  例如:
handle hcurrentthread = getcurrentthread();
//获得该线程句柄
setthreadpriority(hcurrentthread, thread_priority_lowest); 

  6.睡眠
void sleep(dword dwmilliseconds);

  该函数可使线程暂停自己的运行,直到dwmilliseconds毫秒过去为止。它告诉系统,自

身不想在某个时间段内被调度。
  7.其它重要api
  获得线程优先级
  一个线程被创建时,就会有一个默认的优先级,但是有时要动态地改变一个线程的优先

级,有时需获得一个线程的优先级。
int getthreadpriority (handle hthread);

  如果函数执行发生错误,会返回thread_priority_error_return标志。如果函数成功地

执行,会返回优先级标志。
  获得线程退出码
bool winapi getexitcodethread(
 handle hthread,
 lpdword lpexitcode
);

  如果执行成功,getexitcodethread返回true,退出码被lpexitcode指向内存记录;否

则返回false,我们可通过getlasterror()获知错误原因。如果线程尚未结束,lpexitcode

带回来的将是still_alive。
获得/设置线程上下文
bool winapi getthreadcontext(
 handle hthread,
 lpcontext lpcontext
);
bool winapi setthreadcontext(
 handle hthread,
 const context *lpcontext
);

  由于getthreadcontext和setthreadcontext可以操作cpu内部的寄存器,因此在一些高

级技巧的编程中有一定应用。譬如,调试器可利用getthreadcontext挂起被调试线程获取其

上下文,并设置上下文中的标志寄存器中的陷阱标志位,最后通过setthreadcontext使设置

生效来进行单步调试。

  8.实例
  以下程序使用createthread创建两个线程,在这两个线程中sleep一段时间,主线程通

过getexitcodethread来判断两个线程是否结束运行:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
dword winapi threadfunc(lpvoid);
int main()
{
   handle hthrd1;
   handle hthrd2;
   dword exitcode1 = 0;
   dword exitcode2 = 0;
   dword threadid;
   hthrd1 = createthread(null, 0, threadfunc, (lpvoid)1, 0, &threadid);
   if(hthrd1)
      printf("thread 1 launched/n");
   hthrd2 = createthread(null, 0, threadfunc, (lpvoid)2, 0, &threadid);
   if(hthrd2)
      printf("thread 2 launched/n");
   // keep waiting until both calls to getexitcodethread succeed and
   // neither of them returns still_active.
   for (;;)
   {
      printf("press any key to exit../n");
      getch();
      getexitcodethread(hthrd1, &exitcode1);
      getexitcodethread(hthrd2, &exitcode2);
      if(exitcode1 == still_active)
         puts("thread 1 is still running!");
      if(exitcode2 == still_active)
         puts("thread 2 is still running!");
      if(exitcode1 != still_active && exitcode2 != still_active)
         break;
   }
   closehandle(hthrd1);
   closehandle(hthrd2);
   printf("thread 1 returned %d/n", exitcode1);
   printf("thread 2 returned %d/n", exitcode2);
   return exit_success;
}
/*
* take the startup value, do some simple math on it,
* and return the calculated value.
*/
dword winapi threadfunc(lpvoid n)
{
   sleep((dword)n*1000*2);
   return (dword)n * 10;
}

  通过下面的程序我们可以看出多线程程序运行顺序的难以预料以及winapi的

createthread函数与c运行时库的_beginthread的差别:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
dword winapi threadfunc(lpvoid);
int main()
{
   handle hthrd;
   dword threadid;
   int i;
   for (i = 0; i < 5; i++)
   {
      hthrd = createthread(null, 0, threadfunc, (lpvoid)i, 0, &threadid);
      if(hthrd)
      {
         printf("thread launched %d/n", i);
         closehandle(hthrd);
      }
   }
   // wait for the threads to complete.
   sleep(2000);
   return exit_success;
}
dword winapi threadfunc(lpvoid n)
{
   int i;
   for(i = 0; i < 10; i++)
      printf("%d%d%d%d%d%d%d%d/n", n, n, n, n, n, n, n, n);
   return 0;
}

  运行的输出具有很大的随机性,这里摘取了几次结果的一部分(几乎每一次都不同):
 

  如果我们使用标准c库函数而不是多线程版的运行时库,则程序可能输出"3333444444"

这样的结果,而使用多线程运行时库后,则可避免这一问题。
  下列程序在主线程中创建一个secondthread,在secondthread线程中通过自增对

counter计数到1000000,主线程一直等待其结束:
#include <win32.h>
#include <stdio.h>
#include <process.h>
unsigned counter;
unsigned __stdcall secondthreadfunc(void *parguments)
{
   printf("in second thread.../n");
   while(counter < 1000000)
      counter++;
   _endthreadex(0);
   return 0;
}
int main()
{
   handle hthread;
   unsigned threadid;
   printf("creating second thread.../n");
   // create the second thread.
   hthread = (handle)_beginthreadex(null, 0, &secondthreadfunc, null, 0,

&threadid);
   // wait until second thread terminates
   waitforsingleobject(hthread, infinite);
   printf("counter should be 1000000; it is-> %d/n", counter);
   // destroy the thread object.
   closehandle(hthread);
}

 

ZZ:http://www.dnbcw.com/biancheng/xiancheng/BTGC10116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值