Linux中線程的掛起與恢復(進程暫停)


http://www.linuxidc.com/Linux/2013-09/90156.htm

 

今天在網上查了一下Linux中對進程的掛起與恢復的實現,相關資料少的可憐,大部分都是粘貼復制。也沒有完整詳細的代碼。故自己整理了一下

程序流程為:主線程創建子線程(當前子線程狀態為stop停止狀態),5秒后主線程喚醒子線程,10秒后主線程掛起子線程,15秒后主線程再次喚醒子線程,20秒后主線程執行完畢等待子線程退出。

代碼如下:
#include
#include
#include
#include
#include


#define RUN 1
#define STOP 0


pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


int status = STOP;
void * thread_function(void)
{
    static int i = 0;
    while (1) 
    {  
        pthread_mutex_lock(&mut);
        while (!status)
        {
            pthread_cond_wait(&cond, &mut);
        }
        pthread_mutex_unlock(&mut);
    
        printf("child pthread %d\n", i++);
        if (i == 20) 
            break;
        sleep(1);
    }  
}


void thread_resume()
{
    if (status == STOP)
    {  
        pthread_mutex_lock(&mut);
        status = RUN;
        pthread_cond_signal(&cond);
        printf("pthread run!\n");
        pthread_mutex_unlock(&mut);
    }  
    else
    {  
        printf("pthread run already\n");
    }  
}


void thread_pause()
{
    if (status == RUN)
    {  
        pthread_mutex_lock(&mut);
        status = STOP;
        printf("thread stop!\n");
        pthread_mutex_unlock(&mut);
    }  
    else
    {  
        printf("pthread pause already\n");
    }
}


int main()
{
    int err;
    static int i = 0;
    pthread_t child_thread;


#if 0
    if (pthread_mutex_init(&mut, NULL) != 0)
        printf("mutex init error\n");
    if (pthread_cond_init(&cond, NULL) != 0)
        printf("cond init error\n");
#endif


    err = pthread_create(&child_thread, NULL, (void *)thread_function, NULL);
    if (err != 0 )
        printf("can't create thread: %s\n", strerror(err));
    while(1)
    {
        printf("father pthread %d\n", i++);
        sleep(1);
        if (i == 5)
            thread_resume();
        if (i == 10)
            thread_pause();
        if (i == 15)
            thread_resume();
        if (i == 20)
            break;
    }
    if (0 == pthread_join(child_thread, NULL))
        printf("child thread is over\n");
    return 0;
}

相關閱讀:

對Linux中多線程編程中pthread_join的理解 http://www.linuxidc.com/Linux/2013-09/89931.htm

Linux多線程編程時如何查看一個進程中的某個線程是否存活 http://www.linuxidc.com/Linux/2013-09/89930.htm

有關Linux下線程的創建 http://www.linuxidc.com/Linux/2013-08/88530.htm

Linux內核線程死鎖或死循環之后如何讓系統宕機重啟 http://www.linuxidc.com/Linux/2013-04/82063.htm

Linux下C語言實現多線程文件復制 http://www.linuxidc.com/Linux/2013-03/81373.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM