线程的正确结束方式

        在使用C语言进行多线程编程时,最重要的是线程怎么结束,而不是它怎么开始。多线程编程的主要问题,是需要线程“正确”结束,我们在编程中应该尽量避免使用系统提供的使线程强制结束的函数,而应该使用一定的同步方式,保证线程分配的资源得到正确地处理,避免内存泄漏。很多人在进行多线程编程时不注意线程的结束方式,从而及其容易导致程序的内存资源不释放,文件、套接字未关闭。这些问题容易对程序造成伤害,特别是在程序的测试时期导致空指针错误而程序崩溃,而且是非常难以察觉的。以下是需要注意的地方:

(1) 分清每个线程的责任,对于程序资源的初始化和删除尽量在同一个线程中进行。

(2) 使用线程同步,如果A线程初始化资源a,而由B线程来删除,那么使用信号量,互斥量等方式进行同步。

(3) 线程自身的结束。尽量使用pthread_join(Unix)(或者WaitForSingleObject(windows))进行线程等待的结束。同时检查线程的返回值,保证程序的正确性。

(4) 对于进行循环任务的线程,不要使用while(true){Task();}的方式,最好在while循环里放个变量,并在其他线程使用这个标志结束之。

一个参考线程模型(伪码):

 

typedef struct Thread
{
    sys_thread_handle thread_id;   
//relate to system thread handle; for Linux pthread lib, it can be pthread_t;
    bool stoped;       //thread stop flag;
   void *data;         //data relate to thread
}
 thread_t;

//create the thread, this is easy.
thread_t* Thread_create(void * func, int prio, int stacksize, void * args)
{
   
//this is defferent from systems, but most of it is the same.
    thread_t thread = (thread_t*)malloc(sizeof(thread_t));
    thread
->stopped = false;
   
//init data field
    thread->data = malloc(/*....*/);
    sys_thread thread_id 
= thread_create(func, (void*)thread/*the arg*/);
    thread
->thread_id = sys_thread_id;
   
return thread;
}


//exit the thread, this is hard
int Thread_exit(thread_t *thread)
{
    thread
->stopped = true;
    
int error = pthraed_join(thread_id);   //wait for the thread to exit itself.
    if(error)
    
{
        
//error handle
    }

    free(thread
->data); //data malloc by calling thread, so free it also in calling thread
    free(thread);   //
    return 0// or other if error.
}


//thread function, important
void * thread_task(void *arg)
{
      thread_t 
*self = (thread_t*)arg;
     
//init data;
    void * data, otherdata;
    otherdata 
= self->data;
    data 
= malloc(/*.....*/);
   
//....

    
while(!self->stopped)
    
{
        
//some useful task;
    }

    
   
//the data is malloc in the thread, so free it.
   free(data);  
   
return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值