使用pthread做线程控制,锁版

本文介绍了一个控制打印进程的程序,通过输入不同的按键来实现打印进程的启动、暂停、恢复与结束。程序使用了多线程、互斥锁等技术,实现了进程的有序控制。

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

1.开始扫描.
2.继续扫描.
3.暂停扫描.
4.停止扫描.
/*
 * wolegequ.cpp
 *
 *  Created on: 2013-1-20
 *      Author: lj
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <conio.h>
#include "pthread.h"

using namespace std;

#include <time.h>
clock_t start_time, finish_time;
double   duration;

enum Statue
{
	st_null,
	st_start,
	st_pause,
	st_end
};

typedef struct str_thdata
{
	pthread_mutex_t lock;
    Statue bar;
    int index;
} thdata;


void* PrintMessageFunction ( void* ptr )
{
    thdata* data;
    data = (thdata*) ptr;

    int i = data->index;
    for(; data->bar != st_end; i++)
    {
    	printf("index: %d \n", i);
    	Sleep(1000);
    	//printf("statu: %d \n", data->bar);

    	if(data->bar == st_pause)
    	{
    		pthread_mutex_lock(&(data->lock));
    	}
    }

    data->bar = st_null;

    pthread_exit(0);
    return NULL;
}

void* ControlPrintFunction ( void* ptr )
{
    thdata* data;
    data = (thdata*) ptr;

    char ch;

    while(true)
    {
    	ch = getch();

    	if(ch == 's' && data->bar == st_null)
		{
			data->bar = st_start;
			printf("start\n");

			pthread_t thread1;
			pthread_create(&thread1, NULL, PrintMessageFunction, ptr);
			pthread_detach(thread1);
			ch = ' ';
		}

    	else if(ch == 'c')
    	{
    		if(data->bar == st_start)
    		{
				data->bar = st_pause;
				printf("pause\n");
				ch = ' ';
				continue;
    		}
			else if(data->bar == st_pause)
			{
				data->bar = st_start;
				printf("recovery\n");
				pthread_mutex_unlock(&(data->lock));
				ch = ' ';
				continue;
			}
    	}

    	else if(ch == 'e' && data->bar != st_end && data->bar != st_null)
    	{
    		if(data->bar == st_pause)
    		{
    			pthread_mutex_unlock(&(data->lock));
    		}
    		data->bar = st_end;
    		printf("end\n");
    		ch = ' ';
    		continue;
    	}

    	else if(ch == 'x')
    	{
    		break;
    	}
    }

    return NULL;
}

int main()
{
	printf("Press the 's' key to start, press 'c' switching key pause and recovery, \npress the 'e' key end,press the 'x' key exit.\n");

	thdata data1;
	data1.bar = st_null;
	data1.index = 0;
	pthread_mutex_init(&(data1.lock), NULL);
	pthread_mutex_lock(&(data1.lock));
	ControlPrintFunction((void*) &data1);
	pthread_mutex_destroy(&(data1.lock));

	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值