牛骨文教育服务平台(让学习变的简单)
博文笔记

linux c++ 同步、异步简单实例

创建时间:2016-05-23 投稿人: 浏览次数:414

1 概念

所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回。

异步。
当一个异步过程调用发出后,调用者不会立刻得到结果。
实际处理这个调用的部件是在调用发出后,
通过状态、通知来通知调用者,或通过回调函数处理这个调用


异步的实现方式有两种:通过多进程和timmer


下面是实例:

#include <stdio.h>
#include <typeinfo>
#include <stdint.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <aio.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <sys/time.h>
#include <iostream>
void*  sync_func(void * str )
{
  const char *pstr = (const char*)str;
  for(size_t i =0;i<10;i++)
  {
      printf("%s %ld
",pstr,i);
      sleep(1);
  }
}
void sync_signal(int signal_num)
{
  char * str = "hello";
  (void*)sync_func((void *)str);
}
int async_func_multithreads(const char * str)
{
   pthread_t thread;
   pthread_create(&thread,NULL,sync_func,(void*)str);
   return thread;
}

int async_func_timer(const char * str)
{
        //signal(SIGVTALRM, sync_signal);
        signal(SIGALRM, sync_signal);
        struct itimerval  value2,ovalue;
        value2.it_value.tv_sec = 3;
        value2.it_value.tv_usec = 500000;
        value2.it_interval.tv_sec = 10;
        value2.it_interval.tv_usec = 500000;
        setitimer(ITIMER_REAL, &value2, &ovalue);
        //setitimer(ITIMER_VIRTUAL, &value2, &ovalue);
}
int main(void)
{
     char * str="hahahhaha";
     char * str2="wowowoowowo";
     //int thread=async_func_multithreads(str);
     async_func_timer("yesyesyes");
     sync_func((void*)str2);
     //async_func_timer(str);
     std::cout<<"come end"<<std::endl;;
    return 0;
}




声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。