linux线程的挂起和唤醒

本文通过实例代码展示了如何在Linux环境下使用pthread库实现线程的挂起与唤醒功能。线程通过pthread_cond_wait挂起,等待特定条件变量通知后再唤醒继续执行。主程序创建两个线程,一负责周期性地暂停和恢复另一个线程的运行,以此展示线程的控制流程。

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

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

pthread_t IDA;
pthread_t IDB;

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

#define RUN 1
#define STOP 0

int status = RUN;

void * thread_function(void *param)
{
    static int i = 0;
    while (1)
    {
        pthread_mutex_lock(&mut);
        while (!status)
        {
            pthread_cond_wait(&cond, &mut);
        }
        pthread_mutex_unlock(&mut);

        //do actual something
        printf("thread is running...\n");
        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);
    }
}

void thread_pause()
{
    if (status == RUN)
    {
        pthread_mutex_l
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值