linux中线程的挂起与恢复(进程暂停)(2013-06-19 13:42:58)

本文介绍了一个简单的Linux示例程序,演示了如何通过主线程控制子线程的状态,包括挂起(stop)和恢复(run)操作。利用pthread库中的条件变量和互斥锁实现了线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在网上查了一下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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值