打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Linux中线程的挂起与恢复(进程暂停)
userphoto

2015.06.02

关注

今天在网上查了一下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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
pthread_cond_wait()与pthread_cond_signal()
自己写的C语言线程同步的一个测试例子
多线程编程实例---pthread_join函数详解
linux c多线程编程实例代码
linux下C语言多线程编程实例
200行C代码实现简单线程池 - Linux内核编程 - 举世无双的学习之路
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服