Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 中執行緒的掛起與恢復(進程暫停)實作

前陣子上網查了 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;
}

Copyright © Linux教程網 All Rights Reserved