Linux 多线程编程实例

#include<pthread.h>
#include<stdio.h>
#include<string.h>


#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(void *arg)
{
  static int i = 0;
  while(1)
  {
    pthread_mutex_lock(&mut);
    if(!status)
    {
      printf("thread_cond_wait\n");
      pthread_cond_wait(&cond,&mut);
    }
    pthread_mutex_unlock(&mut);
    printf("Thread ID = %d\n",i);
    i++;
    if(i==20)
    {
      break;
    }
    sleep(1);

  }
}



void thread_resume()
{
  if(status == STOP)
  {
      pthread_mutex_lock(&mut);
      status = RUN;
      pthread_cond_signal(&cond);
      pthread_mutex_unlock(&mut);
      printf("thread run\n");

  }
  else
  {
    printf("Thread run already\n");
  }
}

void thread_pause()
{
  if(status == RUN)
  {
    pthread_mutex_lock(&mut);
    status = STOP;
    printf("thread resume\n");
    pthread_mutex_unlock(&mut);

  }
  else
  {
    printf("Thraed Pause already\n");
  }

}


void main()
{

  int errMut = pthread_mutex_init(&mut,NULL);
  int errCond= pthread_cond_init(&cond,NULL);

  if(errMut !=0 || errCond != 0)
  {
    printf("init mut or cond error,return!");
    return;
  }

  pthread_t pt;
  int err = pthread_create(&pt,NULL,thread,NULL);
  if(err!=0)
  {
    printf("create thread error\n");
  }

  int i =0;
  while(1)
  {
    i++;
    sleep(1);
    if(i == 5)
    {
      thread_resume();
    }
    else  if(i==10)
    {
      thread_pause();
    }
    else if(i ==15)
    {
      thread_resume();
    }
    else if(i ==20)
    {
      break;
    }
  }
  printf("Main Thread End\n") ;
  pthread_exit(NULL);
}








                                                        1,1           Top

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值